需求:
后端根据excel模板,填充数据,生成文件,并转换成pdf输出给前端。
实现方式:
1、引入jar:
cn.afterturn
easypoi-spring-boot-starter
4.2.0
e-iceblue
spire.xls.free
5.1.0
system
${basedir}/lib/spire.xls.free-5.1.0.jar
2、打包注意事项
org.springframework.boot
spring-boot-maven-plugin
true
src/main/resources
**/**
false
3、如果能用maven导入的话,就直接按下面的方式引入:
com.e-iceblue
e-iceblue
https://repo.e-iceblue.cn/repository/maven-public/
e-iceblue
spire.xls.free
5.1.0
4、代码使用
tips:模板放到 /resources/doc/下即可。
//根据自己的业务逻辑查询数据
PrintVo printVo = printService.getPrintInfo();
//模板
TemplateExportParams params = new TemplateExportParams(
"doc/print_template.xlsx", false);
//excel数据
Map excelMap = JSONObject.parseObject(JSON.toJSONString(printVo), Map.class);
//数据填充
Workbook workbook = ExcelExportUtil.exportExcel(params, excelMap);
//保存临时文件
File file = new File( "D:/temp/print_temp_file.xlsx");
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
//另存为pdf
File filePdf = new File("D:/temp/print_temp_pdf.pdf");
com.spire.xls.Workbook wb = new com.spire.xls.Workbook();
wb.loadFromFile(file.getAbsolutePath());
wb.saveToFile(filePdf.getAbsolutePath(), FileFormat.PDF);
//关闭流
fos.close();
//后续将filePdf返回给前端,亦或上传到oss再返回给前端url都ok
.....
模板中字段取值按map中的key填写,示例如下:
image.png
=====end!=====
附spire5.1.0 jar包:
链接:https://pan.baidu.com/s/1a1PZGL2cYhD5yvlk2lgbmw?pwd=yqd6
提取码:yqd6