有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在XWPFDocument中插入段落

我正在一台计算机上进行搜索和替换。docx文件,在某些情况下,“替换”文本包含换行符。我已经尝试了一些技巧。第一种方法是将替换文本分成几行,然后执行以下操作:

run.setText(lines[0], 0);
for(int x=1; x<lines.length; x++) {
    run.addCarriageReturn();
    run.setText(lines[x]);
}

结果全部在一行上运行

因此,我进行了一些搜索,找到了用每行一组段落替换现有段落的代码:

private void replaceParagraph(XWPFParagraph p, String[] paragraphs) {
    if (p != null) {
        XWPFDocument doc = p.getDocument();
        for (int i = 0; i < paragraphs.length; i++) {
            XmlCursor cursor = p.getCTP().newCursor();
            XWPFParagraph newP = doc.insertNewParagraph(cursor);
            newP.setAlignment(p.getAlignment());
            newP.getCTP().insertNewR(0).insertNewT(0).setStringValue(paragraphs[i]);
            newP.setNumID(p.getNumID());
        }
        doc.removeBodyElement(doc.getPosOfParagraph(p));
    }
}

问题是InsertNewParague每次都返回null。这可能是因为段落位于表格单元格内,但我没有将其作为原因。我已经检查了光标,还有光标。isStart()为true,似乎符合文档中的要求

Add a new paragraph at position of the cursor. The cursor must be on the XmlCursor.TokenType.START tag of an subelement of the documents body. When this method is done, the cursor passed as parameter points to the XmlCursor.TokenType.END of the newly inserted paragraph.

我已经仔细检查过那个医生了!=null,我想不出任何其他原因可能会返回null。有什么建议吗


共 (1) 个答案

  1. # 1 楼答案

    这最终解决了这个问题

    private void createParagraphs(XWPFParagraph p, String[] paragraphs) {
        if (p != null) {
            XWPFDocument doc = p.getDocument();
            XmlCursor cursor = p.getCTP().newCursor();
            for (int i = 0; i < paragraphs.length; i++) {
                XWPFParagraph newP = doc.createParagraph();
                newP.getCTP().setPPr(p.getCTP().getPPr());
                XWPFRun newR = newP.createRun();
                newR.getCTR().setRPr(p.getRuns().get(0).getCTR().getRPr());
                newR.setText(paragraphs[i]);
                XmlCursor c2 = newP.getCTP().newCursor();
                c2.moveXml(cursor);
                c2.dispose();
            }
            cursor.removeXml(); // Removes replacement text paragraph
            cursor.dispose();
        }
    }