Apache POI无法识别Word文档部分模板的技术问题求助
Apache POI处理Word模板时部分占位符无法替换的问题
我在使用Apache POI处理Word文档时遇到问题:部分模板占位符可正常识别替换,但有一些无法被检测到,未被检测的占位符在输出文档中保持不变。
例如,[owner]和[serialNumber]能被正常替换,但[controlType]无法被替换。我通过Word的CTRL+F功能复制粘贴占位符搜索,可正常找到所有模板,排除了文档本身的问题。
代码实现
@Override public byte[] generateSingleScale(SingleScale singleScale) { // Getting file try { XWPFDocument doc = new XWPFDocument(new FileInputStream(wordFile)); for (XWPFTable table : doc.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { for (XWPFParagraph paragraph : cell.getParagraphs()) { String text = paragraph.getText(); if (text != null) { // Conditional replacements if (text.contains("[controlType]")) { replaceText(paragraph, "[controlType]", singleScale.getControlType()); } if (text.contains("[owner]")) { replaceText(paragraph, "[owner]", singleScale.getOwner()); } if (text.contains("[serialNumber]")) { replaceText(paragraph, "[serialNumber]", jednodelnoMerilo.getSerialNumber()); } // More conditional replacements } } } } } // Rest of the code return workingDocumentBytes; } catch (IOException e) { e.printStackTrace(); return null; } } private void replaceText(XWPFParagraph paragraph, String placeholder, String replacement) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); if (text != null && text.contains(placeholder)) { run.setText(text.replace(placeholder, replacement), 0); } } }
使用的依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.5</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.2.5</version> </dependency>
我使用的是Word 2010,尝试过修改代码实现方式、更换模板内容、检查文档中模板的字号和字体,但问题仍未解决。
内容的提问来源于stack exchange,提问作者Jovan Stankovic
相关产品推荐
相关产品推荐

