近期项目工作需要动态生成Word文档的需求,特意调研了动态生成Word的技术方案。主要有以下两种:
- 第一种是FreeMarker模板来进行填充;
- 第二种是POI-TL技术使用Word模板来进行填充;
以下是关于POI-TL的官方介绍
重点关注:word模版一定、一定、一定要使用Microsoft Word来进行生成,不能使用WPS或其他工具生成。
本例按一下步骤进行讲解
1、准备Word模版文件
2、创建SpringBoot工程并配置pom.xml文件
<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.10.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>4.1.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.7</version></dependency>
3、创建实体对象
Device.java
@Data
@ApiModel
public class Device {@ApiModelProperty(value = "设备ID",name = "deviceId")private Long deviceId ;/** 装备名称 */@ApiModelProperty(value = "设备名称",name = "deviceName")private String deviceName ;/** 装备类型 */@ApiModelProperty(value = "设备类型",name = "deviceType")private String deviceType ;/** 装备型号 */@ApiModelProperty(value = "设备型号",name = "deviceModel")private String deviceModel ;/** 装备用途 */@ApiModelProperty(value = "设备用途",name = "deviceUse")private String devicetUse ;/** 生产厂家 */@ApiModelProperty(value = "生产厂家",name = "manufacturer")private String manufacturer ;/** 采购日期 */@JsonFormat(pattern = "yyyy-MM-dd")@ApiModelProperty(value = "采购日期(yyyy-MM-dd)",name = "purchaseDate")private Date purchaseDate ;
3、编写数据渲染逻辑
String templateTargetPath = "D:"+ File.separator + "P" + RandomUtil.randomNumbers(10) + ".docx";File templateTargetFile = new File(templateTargetPath);Map<String, Object> mapData = new HashMap();mapData.put("deviceList", deviceList);mapData.put("pipeList", pipeList);mapData.put("taskName", "测试任务"); //渲染数据LoopRowTableRenderPolicy loopRowTableRenderPolicy = new LoopRowTableRenderPolicy();Configure configure = Configure.builder().bind("deviceList", loopRowTableRenderPolicy).bind("pipeList", loopRowTableRenderPolicy).build();//读取模板文件InputStream inputStream = new FileInputStream(new File(templatePath+ File.separator + "方案信息.docx"));XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(mapData);//目标文件template.writeToFile(templateTargetPath);template.close();
注:LoopRowTableRenderPolicy
是一个特定场景的插件,根据集合数据循环表格行。
表格动态内容填充,POI-TL提供了3种方式。
- 表格行循环
- 表格列循环
- 动态表格。