0

我发现人们使用 docx4j 来修改 docx。我经历了“入门”,我相信我对这个 lib 作品有基本的了解。

我想要实现的是将基本文本添加到文档的开头(在任何其他文本之前)。我设法将文本添加到文件末尾。这是代码:

    for(File file: folder.listFiles())
    {
        if(file.getName().contains("docx"))
        {
            try
            {
                WordprocessingMLPackage docx = WordprocessingMLPackage.load(file);
                docx.getMainDocumentPart().addParagraphOfText(toAppend);
                docx.save(new File(file.getAbsolutePath()));
            }
            catch (Docx4JException e)
            {
                e.printStackTrace();
            }
        }
    }

但它的行为不像我预期的那样。它将文本附加到 eof。如何在 MainDocumentPart 之前而不是之后添加文本?此外,我想保持代码简洁易读。

4

2 回答 2

3

这是一个简单的方法,可以满足您的要求:

    public org.docx4j.wml.P addParaAtIndex(MainDocumentPart mdp, String simpleText, int index) {

    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.P  para = factory.createP();

    if (simpleText!=null) {
        org.docx4j.wml.Text  t = factory.createText();
        t.setValue(simpleText);

        org.docx4j.wml.R  run = factory.createR();
        run.getContent().add(t); 

        para.getContent().add(run); 
    }

    mdp.getContent().add(index, para);

    return para;
}

在此示例中,我没有费心检查 IndexOutOfBoundsException

于 2013-10-08T00:04:31.463 回答
1

我不知道用 docx4j 做到这一点的方法,但我对那个库也不是很熟悉。如果您想尝试不同的库,则可以下载Apache POI并执行以下操作:

for(File file: folder.listFiles())
{
    if(file.getName().contains("docx"))
    {
        try
        {
            HWPFDocument docx= new HWPFDocument(new java.io.FileInputStream(file));
            docx.getRange().insertBefore(toAppend);
            FileOutputStream fileOut = new FileOutputStream(file);
            docx.write(fileOut);
            fileOut.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
于 2013-10-07T23:10:05.237 回答