????????近期項目工作需要動態生成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種方式。
- 表格行循環
- 表格列循環
- 動態表格。