1分钟用EasyExcel实现文件下载
中国人不骗中国人,说一分钟,就只需要一分钟。
哈喽,大家好,我是一条。
相信大家在工作中都遇到过「导出」或「下载」的需求,简单来说就是将数据导出到 Excel 然后下载到客户端本地。
主流的实现的方式有三种:
- Apache POI,较原始的开源框架,代码量大,对 2003 和2007 的 Excel 需要分开处理,个人觉得是最大痛点。
- Easy Excel ,阿里开源,代码简单,上手迅速,推荐在不是特别复杂的场景使用。
- Easy Poi ,同样代码简单,可实现复杂场景。
本文主要介绍如何快速应对简单的业务场景,所以使用 Easy Excel 。
话不都说,开干。
导入pom
先建一个 Spring Boot 工程,不多说。导入 maven 依赖。(5秒)
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.10</version>
</dependency>
实体类
一般导出的数据都对应数据库的一个实体,我们直接在字段上加注解即可。(15秒)
@ExcelProperty("销售战区") // 对应表格中的表头
private String saleZone;
@ExcelIgnore // 表示该字段不需要导出
private Date updateTime;
构建导出数据
一般导出功能都对应一个查询接口,我们只需要简单修改一下(或者直接用)即可,这里用 Mybatis-Plus 举例实现。(10秒)
public List<ZoneReportPO> getReportList() {
return zoneReportMapper.selectList(Wrappers.lambdaQuery(ZoneReportPO.class));
}
Controller
最后一步,编写controller。直接复制下面代码,然后修改一下文件名即可,干净利落。(10秒)
@GetMapping("/report/download")
public void download(HttpServletResponse response) throws IOException {
// 改成你想要的文件名
String fileName = "filename" + DateUtil.date().toDateStr() + ".xls";
response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), ZoneReportPO.class).build();
// 调用上一步构建数据的方法
excelWriter.write(zoneReportService.getReportList(), EasyExcel.writerSheet("sheet1").build());
excelWriter.finish();
}
启动测试
重启你的工程,浏览器访问测试,注意用浏览器,别用 postman 或者 swagger 等工具。(15秒)
注意,不需要先定义模板。这里EasyExcel.write(response.getOutputStream(), ZoneReportPO.class)
传的是一个输出流,会根据注解自动帮我们生成表头。
还剩5秒?
还剩5秒?
别愣着了,点赞关注吧!
转载自:https://juejin.cn/post/7091168950351986725