使用 阿里巴巴的 EasyExcel 填充 excel模板导出,需要支持批量操作,即一个模板循环导出多份,在网上找了下其他大佬们的做法,没有找到想要的,很多都是要先生成excel文件,再压缩导出,但我不想这样做,想直接通过文件流的方式,直接导出,经下午修改测试,成功达到了我想要的效果。
一、导包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.3</version>
</dependency>
二、主要的逻辑代码
public void doExportTemplateExcel(HttpServletResponse response) {
//获取模板文件,模板文件需放在 resource下
String templateExcelFileName = "xxx导出模板.xlsx";
InputStream templateExcelInputStream = this.getClass().getClassLoader().getResourceAsStream("template" + File.separatorChar + templateExcelFileName);
if (null == templateExcelInputStream) {
throw new SystemException("模板文件不存在!");
}
ByteArrayOutputStream outputStream = null;
ZipOutputStream zipOut = null;
try {
//处理导出的zip 文件名称,避免中文乱码
response.setContentType("application/octet-stream; charset=UTF-8");
String encodedFileName = URLEncoder.encode("XXX导出.zip", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename*=utf-8''" + encodedFileName);
zipOut = new ZipOutputStream(response.getOutputStream());
//复制输入模板文件流,避免第一次以后读取为空问题
ByteArrayOutputStream bos = cloneInputStream(templateExcelInputStream);
for (int i = 0; i < 10; i ++) {
InputStream copyInputStream = new ByteArrayInputStream(bos.toByteArray());
outputStream = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(copyInputStream).excelType(ExcelTypeEnum.XLSX).build();
//设置 zip 中的每个文件名称
zipOut.putNextEntry(new ZipEntry("导出excel文件- " + i + templateExcelFileName.substring(templateExcelFileName.lastIndexOf("."))));
WriteSheet writeSheet = EasyExcel.writerSheet().build();
FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
/****************** 值填充逻辑开始,请按实际业务修改 ************************/
excelWriter.fill(() -> {
List<Map> dataList = new ArrayList<>();
for (int j = 0; j < 10; j ++) {
Map temp = new HashMap();
temp.put("index", j);
temp.put("no", "No " + j);
temp.put("name", "名称 " + j);
dataList.add(temp);
}
return dataList;
}, fillConfig, writeSheet);
Map map = new HashMap();
map.put("applyStaffName", "提交人");
map.put("applyOrgName", "提交部门");
map.put("createDate", new SimpleDateFormat("yyyyMMdd").format(new Date()));
map.put("orderSn", "SN12345");
map.put("description", "我是备注");
excelWriter.fill(map, writeSheet);
/****************** 值填充逻辑结束,请按实际业务修改 ************************/
excelWriter.finish();
outputStream.writeTo(zipOut);
outputStream.flush();
outputStream.close();
zipOut.closeEntry();
copyInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("导出 excel -> zip 时出现异常" + e.getMessage());
} finally {
if (null != outputStream) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != zipOut) {
try {
zipOut.flush();
zipOut.finish();
zipOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 复制InputStream
*
* InputStream inputStream = new ByteArrayInputStream(ByteArrayOutputStream.toByteArray());
* @param input
* @return
*/
public static ByteArrayOutputStream cloneInputStream(InputStream input) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
以上主要业务逻辑代码仅为实现业务的概要代码,仅作为解决思路指引和参考,如需在正式项目中使用,请根据实际业务逻辑进行修改,并增加对应的导出数据获取、处理以及异常处理等逻辑。
三、执行结果
代码执行成功后,会下载一个 zip压缩包,压缩包里面放的就是代码中通过 excel模板生成的 excel文件。
注:
执行结果截图为我当前实际业务截图,非上述概要业务代码执行结果,所以文件名称和代码中的设置会不一样。