【发布时间】:2013-01-27 15:33:30
【问题描述】:
我正在使用 apache poi 3.8 将值写入 word 模板。我用所需的值替换 word 文件(键)中的特定字符串,例如word 文档有一段包含键 %Entry1%,我想用“Entry text line1 \nnew line”替换它。在我的实现中,所有替换的键和值都存储在 Map 中。
Map<String, String> replacedElementsMap;
HWPFDocument 的代码是:
Range range = document.getRange();
for(Map.Entry<String, String> entry : replacedElementsMap.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
此代码运行良好,我只需将 \n 放入输入字符串中即可换行。但是我找不到 XWPFDocument 的类似方法。我当前的 XWPFDocument 代码是:
List<XWPFParagraph> xwpfParagraphs = document.getParagraphs();
for(XWPFParagraph xwpfParagraph : xwpfParagraphs) {
List<XWPFRun> xwpfRuns = xwpfParagraph.getRuns();
for(XWPFRun xwpfRun : xwpfRuns) {
String xwpfRunText = xwpfRun.getText(xwpfRun.getTextPosition());
for(Map.Entry<String, String> entry : replacedElementsMap.entrySet()) {
if (xwpfRunText != null && xwpfRunText.contains(entry.getKey())) {
xwpfRunText = xwpfRunText.replaceAll(entry.getKey(), entry.getValue());
}
}
xwpfRun.setText(xwpfRunText, 0);
}
}
现在“\n”字符串不会导致回车,如果我使用xwpfRun.addCarriageReturn();,我只会在段落后换行。我应该如何在 xwpf 中正确创建新行?
【问题讨论】:
-
如果您在 Office 的段落中添加换行符,然后查看生成的 XML,这是否提供了所需内容的线索?
-
XML 确实包含换行符,但我希望在每个换行符之后有一个新的换行符,所以最后我不得不手动创建新的段落。
标签: java apache apache-poi xwpf