需求:
后端根据excel模板,填充数据,生成文件,并转换成pdf输出给前端。
实现方式:
1、引入jar:
<!--easypoi相关依赖-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<!-- 转换工具-->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
<scope>system</scope>
<systemPath>${basedir}/lib/spire.xls.free-5.1.0.jar</systemPath>
</dependency>
2、打包注意事项
<!-- 注意:将lib中的文件打到jar中,否则会提示找不到类-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<resources>
<!-- 需要把模板文件打包进去-->
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/**</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
3、如果能用maven导入的话,就直接按下面的方式引入:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
</dependency>
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填写,示例如下:
=====end!=====
附spire5.1.0 jar包:
链接:https://pan.baidu.com/s/1a1PZGL2cYhD5yvlk2lgbmw?pwd=yqd6
提取码:yqd6