文章目錄
- 概要
- 整體架構流程
- 創建word模板
- 核心代碼
- 導出結果
概要
在軟件開發領域,自定義Word模板的使用是導出格式化數據的一種常見做法。poi-tl(Apache POI Template Language)作為一款基于廣受認可的Apache POI庫的Word模板引擎,它以純Java組件的形式提供服務,確保了跨平臺的兼容性。poi-tl以其簡潔高效的代碼著稱,不僅易于集成,還通過其插件機制實現了功能的高度可擴展性,允許開發者根據項目需求靈活定制。這一特性使得poi-tl成為處理Word文檔生成任務時的一個強有力工具。
整體架構流程
官網:poi-tl
<!-- POI 依賴 使用xlsx xml的格式(即XSSFWorkbook) --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.17</version></dependency><!-- poi模板導入,主力包 --><dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.12.1</version></dependency>
創建word模板

核心代碼
try {String pictureUrl = "D:\\file\\test\\image\\bigPicture10.jpeg";if (pictureUrl != null && !pictureUrl.isEmpty()) {PictureRenderData picture = Pictures.ofLocal(pictureUrl).size(40, 30).create();finalMap.put("signPicture", picture);}} catch (Exception e) {e.printStackTrace();}// 從classpath加載Word模板文件到臨時文件try (InputStream inputStream = TestWord.class.getClassLoader().getResourceAsStream("template.docx")) {if (inputStream == null) {throw new RuntimeException("無法找到模板文件:template.docx");}// 創建一個臨時文件用于XWPFTemplate處理Path tempFilePath = Files.createTempFile("word-template-", ".docx");Files.copy(inputStream, tempFilePath, StandardCopyOption.REPLACE_EXISTING);// 使用臨時文件作為模板File wordTemplate = tempFilePath.toFile();LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();Configure build = Configure.builder().bind(policy, "workList").build();XWPFTemplate render = XWPFTemplate.compile(wordTemplate, build).render(finalMap);// 定義輸出路徑String outputPath = "D:\\file\\htht\\project\\260\\開發\\output.docx"; // 修改為期望的輸出文件路徑File outputFile = new File(outputPath);try {if (!outputFile.getParentFile().exists()) {outputFile.getParentFile().mkdirs(); // 確保父目錄存在}render.writeToFile(outputFile.getAbsolutePath());System.out.println("Word文檔成功導出到: " + outputPath);} catch (IOException e) {throw new RuntimeException("無法寫入文件: " + e.getMessage(), e);}// 刪除臨時文件(可選)Files.deleteIfExists(tempFilePath);} catch (IOException e) {throw new RuntimeException("讀取模板文件失敗: " + e.getMessage(), e);}
?導出結果

資源提取:https://download.csdn.net/download/yy12345_6_/90275767