1,依赖
<!-- 3.1.1及以上可以支持分批下载 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
2,编码
通用步骤:
1,构建sheet :设置sheet名称、格式
2,构建ExcelWriter:构建流,excel类型等
3,通过excelWriter将数据写入sheet
1,全量下载
/**
* write data to excel
* @param response : 要写入的流
* @param data : 数据
* @throws Exception
*/
private void writeData(HttpServletResponse response, List<List<String>> data, String filename) throws Exception {
EasyExcel.write(getOutputStream(filename, response), List.class) // 每行的映射类型
.excelType(ExcelTypeEnum.XLSX)
.sheet("sheet1")
.registerWriteHandler(getSheetStyle())
.doWrite(data);
}
/**
* 设置响应流格式
* @param fileName 导出的文件名
* @param response 响应流
* @return
* @throws Exception
*/
private OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
response.addHeader("Access-Control-Expose-Headers", "Content-disposition");
return response.getOutputStream();
}
/**
* set sheet style
* @return
*/
private HorizontalCellStyleStrategy getSheetStyle() {
//表头样式
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置表头居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
//内容样式
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置内容靠左对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
2,分批下载
// 1, 构建sheet标签:sheet,easyexcel,写入,fileName,write,data,response,下载 From: https://www.cnblogs.com/junc0125/p/17965044
WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").registerWriteHandler(getSheetStyle()).build();
// 2, 构建ExcelWriter
try(ExcelWriter excelWriter = EasyExcel.write(getOutputStream(fileName, response), List.class).excelType(ExcelTypeEnum.XLSX).build()) {
// 写入表头
excelWriter.write(data, writeSheet);
// 批次
int batchNum = count / InnerConst.BATCH_SIZE;
batchNum += count % InnerConst.BATCH_SIZE == 0 ? 0 : 1;
//分批写入数据
for (int i = 1; i <= batchNum; i++) {
// 获取分批数据
List<List<String>> batchData = getQueryData(req);
// 写入数据
excelWriter.write(batchData, writeSheet);
// 释放内存
batchData.clear();
}
} catch (AppPortalException e) {
e.printStackTrace();
}