制作包含所有内容和属性的段落的精确副本?

时间:2014-04-16 14:51:19

标签: java apache-poi

我试图将一个段落的精确副本复制到另一个段落中(我将模板复制到新文档以进行单词替换)。我是为表格单元格中的段落执行此操作,但我不相信这很重要。以下代码几乎可以使用:

for (XWPFParagraph p : cell.getParagraphs()) {
    XWPFParagraph np = newCell.addParagraph();
    np.getCTP().set(p.getCTP());
}

问题是,虽然np.getCTP().xmlText().equals(p.getCTP().xmlTest()为真,但np.getText()为空,而p.getText()具有段落内容。看起来我的段落并不知道我对XML所做的根本改变。这导致我的输出文档包含占位符文本,因为我的代码似乎无法再查看段落的内容以执行替换。

如何制作包含所有内容和属性的段落的完美副本?

2 个答案:

答案 0 :(得分:9)

这似乎正在完成工作。我不确定整个cloneRun()方法无法被nr.getCTR().set(r.getCTR());取代,但这似乎比抱歉更安全。

public static void cloneParagraph(XWPFParagraph clone, XWPFParagraph source) {
    CTPPr pPr = clone.getCTP().isSetPPr() ? clone.getCTP().getPPr() : clone.getCTP().addNewPPr();
    pPr.set(source.getCTP().getPPr());
    for (XWPFRun r : source.getRuns()) {
        XWPFRun nr = clone.createRun();
        cloneRun(nr, r);
    }
}

public static void cloneRun(XWPFRun clone, XWPFRun source) {
    CTRPr rPr = clone.getCTR().isSetRPr() ? clone.getCTR().getRPr() : clone.getCTR().addNewRPr();
    rPr.set(source.getCTR().getRPr());
    clone.setText(source.getText(0));
}

答案 1 :(得分:0)

    public XWPFParagraph copyParagraph(int currentParagraphIndex)
    {
        List<XWPFParagraph> paragraphs = wordDocument.getParagraphs();

        //get whatever paragraph we're working with from the list
        XWPFParagraph paragraph = paragraphs.get(currentParagraphIndex);

        XmlCursor cursor = paragraph.getCTP().newCursor();
        //inserts a blank paragraph before the original one
        paragraph.getDocument().insertNewParagraph(cursor);

        //make a fully parsed copy of the old paragraph
        XWPFParagraph newParagraph = new XWPFParagraph((CTP) paragraph.getCTP().copy(),wordDocument);

        //update the document with our now paragraph replacing the blank one with our new one and cause the document to reparse it. 
        //Not sure why, but any modification to the new paragraph must be performed prior to setting it. 
        wordDocument.setParagraph(newParagraph,currentParagraphIndex);

        return newParagraph;
    }