阿里开源工具 EasyExcel
孙玉超
2020-10-27 13:33:26
评论
1461 浏览
收藏
0 赞
最近发现一款超好用的 Excel 工具,使用简单。阿里的 EasyExcel,据网上说,阿里重写了原来的 poi 对 Excel 的解析,降低对内存的消耗,并且不会出现内存溢出。也做了一定的封装,让使用者更加简单方便。
首先引入 maven 依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.3</version>
</dependency>然后只要定义好实体类,字段。然后在字段上面用 @ExcelProperty 注解,表示导出时这个字段是要导出的字段,注解的 value 代表表头,使用 @ExcelIgnore 注解表示导出时这个字段被忽略。 如果需要跨列或者跨行,使用 @ContentLoopMerge 注解。示例代码:
@Data
public class RespMemberDossierExcel {
@ExcelIgnore
private Long id;
@ExcelProperty(value = "会员账号", index = 0)
private String username;
@ExcelProperty(value = "会员名称", index = 1)
private String name;
@ExcelProperty(value = "会员归属/创建人手机号", index = 2)
private String createBy; //创建人手机号
@ExcelProperty(value = "会员姓名/拜访对象", index = 3)
private String visitName;//会员姓名
@ExcelProperty(value = "门店地址", index = 4)
private String storeAddress;
}然后在控制器里或者服务层定义好文件名,设置好 response 的 header,调用阿里的 Excel 提供的API即可,示例代码:
String fileName = URLEncoder.encode("会员档案列表.xlsx", StandardCharsets.UTF_8.toString());
response.setHeader(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName);
EasyExcelFactory.write(response.getOutputStream(), RespMemberDossierExcel.class)
.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
.sheet("会员档案列表")
.doWrite(list);最后的 EasyExcelFactory 为返回 Excel 文件流的代码,指定泛型,将数据集合传入即可。示例结果如下: