阿里巴巴 EasyExcel 导出 (4.模板填充 简单的填充)

1.准备一个excel模板(07格式xlsx)

需求1:标题需要动态指定

需求2:数据需要导出多行


2.接口层代码

@SneakyThrows    @RequestMapping("fillSimple")    public ResponseEntity fillSimple(HttpServletRequest req){        // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替        // {} 代表普通变量 {.} 代表是list的变量        //设定需要填充到模板的数据        Map map = new HashMap();        map.put("year","2022");        List list = new ArrayList<>();        list.add(new FillSimpleDTO().setStr("老张").setNum(1));        list.add(new FillSimpleDTO().setStr("老李").setNum(2));        ClassPathResource classPathResource = new ClassPathResource("otherFiles/fillSimple.xlsx");        try(            ByteArrayOutputStream os = new ByteArrayOutputStream();            InputStream inputStream = classPathResource.getInputStream();        ){            //如果你的模板有list,且list不是最后一行,下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();            ExcelWriter excelWriter = EasyExcel.write(os).withTemplate(inputStream).build();            WriteSheet writeSheet = EasyExcel.writerSheet().build();            excelWriter.fill(map,writeSheet);//填充map            excelWriter.fill(list,fillConfig,writeSheet);//填充list            excelWriter.finish();//不要忘记执行这个方法,执行后才能真正填充数据            byte[] bytes = os.toByteArray();            return FileTool.createResEntity(req,bytes,"导出.xlsx");        }    }

FileTool.java 下载用到的工具类

package com.example.support.tools;import org.springframework.http.HttpHeaders;import org.springframework.http.HttpStatus;import org.springframework.http.MediaType;import org.springframework.http.ResponseEntity;import javax.servlet.http.HttpServletRequest;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;/** * @author LWB * @Description */public class FileTool {    /**     * 创建ResponseEntity对象,用于下载字节数组文件     * @param req 请求     * @param data 文件字节数组     * @param fileName 下载时显示的文件名     * @return     */    public static ResponseEntity createResEntity(HttpServletRequest req, byte[] data, String fileName){        HttpHeaders headers = new HttpHeaders();        try {            headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));        } catch (UnsupportedEncodingException e) {            throw new RuntimeException(e.getMessage());        }        //设置响应方式为二进制,以二进制流传输        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);        return new ResponseEntity(data,headers, HttpStatus.OK);    }}

3.测试发送请求

浏览器地址栏输入

localhost:54321/excel/fillSimple

得到返回的导出文件



ok,简单的导出,到此结束.基本可以满足常规的导出需求了

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章