EasyExcel简介
Java领域解析、生成Excel比较有名的框架有Apache poi、jxl等。但他们都存在一个严重的问题就是非常的耗内存。如果你的系统并发量不大的话可能还行,但是一旦并发上来后一定会OOM或 者JVM频繁的full gc。
EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称。EasyExcel能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一 行行读取数据,逐个解析。
EasyExcel采用一行一行的解析模式,并将一行的解析结果以观察者的模式通知处理 (AnalysisEventListener)
SpringBoot整合easyexcel
easyexcel提供读、写、填充三种功能。这里我们采用模板填充的方式实现excel导出。
引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
数据传输实体
@Data
@TableName("demo")
@AllArgsConstructor
@NoArgsConstructor
public class DemoEntity {
/**
* 主键id primary key
*/
@TableId(type = IdType.ASSIGN_ID)
@ExcelProperty(index = 0, value = "主键id")
private Long id;
/**
* 姓名
*/
@TableField("userName")
@ExcelProperty(index = 1, value = "姓名")
private String userName;
/**
* 成绩
*/
@TableField("score")
@ExcelProperty(index = 2, value = "成绩")
private Integer score;
/**
* 性别
*/
@TableField("gender")
private String gender;
service层
public Result outputStream(DemoEntity demo, HttpServletResponse httpServletResponse) throws UnsupportedEncodingException {
QueryWrapper<DemoEntity> wrapper = new QueryWrapper<>();
List<DemoEntity> list = demoMapper.selectList(wrapper);
try {
httpServletResponse.setContentType("application/vnd.ms-excel");
httpServletResponse.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("demo", "UTF-8");
httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//单个shell页
EasyExcel.write(httpServletResponse.getOutputStream(), DemoReq.class).autoCloseStream(Boolean.FALSE).sheet("模板")
.doWrite(list);
//多个shell
// ExcelWriter excelWriter = EasyExcel.write(httpServletResponse.getOutputStream()).build();
// WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "sheet1").build();
// WriteSheet writeSheet2 = EasyExcel.writerSheet(1, "sheet2").build();
// excelWriter.write(list, writeSheet1);
// excelWriter.write(list, writeSheet2);
// excelWriter.finish();
// httpServletResponse.flushBuffer();
} catch (IOException e) {
throw new RuntimeException(e);
}
return null;
}
测试excel导出