在XWPFDocument的段落中插入换行符

Vla*_*kiy 7 java apache apache-poi xwpf

我正在使用apache poi 3.8将值写入单词模板.我用单词文件(键)替换所需值的特定字符串,例如word文档有一个包含键%Entry1%的段落,我想用"Entry text line1 \nnew line"替换它.所有替换的键和值都存储在我的实现中的Map中.

Map<String, String> replacedElementsMap;
Run Code Online (Sandbox Code Playgroud)

HWPFDocument的代码是:

Range range = document.getRange();
for(Map.Entry<String, String> entry : replacedElementsMap.entrySet()) {
            range.replaceText(entry.getKey(), entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)

这段代码工作正常,我只需要将\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);
            }
        }
Run Code Online (Sandbox Code Playgroud)

现在"\n"-string不会导致回车,如果我使用, xwpfRun.addCarriageReturn();我只是在段落后得到一个换行符.我应该如何正确地在xwpf中创建新行?

jac*_*mis 19

我有另一个解决方案,它更容易:

            if (data.contains("\n")) {
                String[] lines = data.split("\n");
                run.setText(lines[0], 0); // set first line into XWPFRun
                for(int i=1;i<lines.length;i++){
                    // add break and insert new text
                    run.addBreak();
                    run.setText(lines[i]);
                }
            } else {
                run.setText(data, 0);
            }
Run Code Online (Sandbox Code Playgroud)

  • 我使用了`run.addCarriageReturn();`,但是不起作用。根据您的建议,更改为`run.addBreak`之后,可以正常工作。很好,但是...为什么? (2认同)