我正在使用apache poi 3.8向word模板中写入值。我使用替换特定字符串(键)的方式将需要的值替换到Word文件中,例如Word文档包含一个包含键%Entry1%的段落,我想用“Entry text line1 \n new 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中创建新行?