【发布时间】:2019-08-25 21:24:17
【问题描述】:
我有一个用作模板的 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
【问题讨论】:
-
发生了什么?
-
您希望所有字符串都在同一个单元格中,还是每个字符串在一个单元格中?当前输出是多少?
-
感谢您的快速帮助。我用模板的一部分更新了问题。希望它会变得更清楚。
-
如果您正在查看我的答案,您会看到 Minimal, Reproducible Example。我们需要您展示您正在使用的代码。请在我们可以下载的地方上传
Word模板。只有这样我们才能重现您的问题。 -
阿克塞尔,我更新了代码。它仍然不是一个最小的、可重现的例子。如果你需要,我会在星期一尝试创建一个。我提供了模板的下载链接。希望有帮助。我仍然坚持这个编辑。非常感谢您的支持。
标签: java ms-word apache-poi