我有一个用作模板的Word文档。在这个模板中,我有一些包含预定义符号点的表格。现在我正在尝试用一组字符串替换占位符字符串。
我完全陷入了困境。我的简化方法如下。
replaceKeyValue.put("[DescriptionOfItem]", new HashSet<>(Collections.singletonList("This is the description")));
replaceKeyValue.put("[AllowedEntities]", new HashSet<>(Arrays.asList("a", "b")));
replaceKeyValue.put("[OptionalEntities]", new HashSet<>(Arrays.asList("c", "d")));
replaceKeyValue.put("[NotAllowedEntities]", new HashSet<>(Arrays.asList("e", "f")));
try (XWPFDocument template = new XWPFDocument(OPCPackage.open(file))) {
template.getTables().forEach(
xwpfTable -> xwpfTable.getRows().forEach(
xwpfTableRow -> xwpfTableRow.getTableCells().forEach(
xwpfTableCell -> replaceInCell(replaceKeyValue, xwpfTableCell)
)
));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
template.write(baos);
return new ByteArrayResource(baos.toByteArray());
} finally {
if (file.exists()) {
file.delete();
}
}
private void replaceInCell(Map<String, Set<String>> replacementsKeyValuePairs, XWPFTableCell xwpfTableCell) {
for (XWPFParagraph xwpfParagraph : xwpfTableCell.getParagraphs()) {
for (Map.Entry<String, Set<String>> replPair : replacementsKeyValuePairs.entrySet()) {
String keyToFind = replPair.getKey();
Set<String> replacementStrings = replacementsKeyValuePairs.get(keyToFind);
if (xwpfParagraph.getText().contains(keyToFind)) {
replacementStrings.forEach(replacementString -> {
XWPFParagraph paragraph = xwpfTableCell.addParagraph();
XWPFRun run = paragraph.createRun();
run.setText(replacementString);
});
}
}
}
我原本期望在当前单元格中添加更多的项目符号,是否有遗漏?该段落是包含占位符字符串和格式的那个。
感谢任何帮助!
更新:以下是模板的部分外观。我想自动搜索这些术语并替换它们。到目前为止,搜索正常进行。但尝试替换项目符号会导致无法定位的 NullPointer
。
使用字段会更容易吗?但我需要保留项目符号样式。
更新2:添加下载链接并更新了代码。如果我正在迭代段落,则似乎无法更改段落。我得到一个空指针。 WordTemplate下载链接
Word
模板上传到我们可以下载的某个地方。只有这样我们才能重现您的问题。 - Axel Richter