【问题标题】:Make an exact copy of a paragraph including all contents and properties?制作包含所有内容和属性的段落的精确副本?
【发布时间】:2019-12-19 00:27:10
【问题描述】:

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

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 所做的基本更改。这导致我的输出文档包含占位符文本,因为我的代码似乎无法再看到段落的内容以执行替换。

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

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

    这似乎完成了工作。我不确定整个 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));
    }
    

    【讨论】:

    • 这正是我所需要的。非常感谢!!
    • 我正在使用这段代码,我发现行前的间距发生了变化。克隆后尝试使用np.setSpacingAfterLines(0);,没有任何结果。此外,源文本使用 Times New Roman,而目标文本使用 Calibri。
    • @FranciscoBouza 不用花太多时间在上面,我唯一能建议的就是查看 docx 文件的 xml 源代码,看看你是否能弄清楚是什么设置了字体和线条间距并寻找 Poi 函数来专门解决这些属性。我相信我的一位同事遇到了这个问题。我会检查他是否解决了问题。
    【解决方案2】:
        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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2011-02-22
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多