使用Java替换Word文档中的数据

时间:2018-07-11 13:31:53

标签: java ms-word

如何替换MS Word文档模板中的数据? 我看过一篇文章,但是它使用了Maven库,由于某种原因,它对我不起作用。 article link

同时,我正在使用Apache POI库,如何获得与上述文章相同的结果?

(我知道如何在Java中创建MS Word文档,但是格式设置并不容易,所以我考虑使用现成的填充模板并替换所需的数据)

修改 我没有得到想要的输出,因此遇到了问题。 这是代码:

    public static void main(String[] args) throws FileNotFoundException, InvalidFormatException, IOException {
    XWPFDocument document = new XWPFDocument(OPCPackage.open("/Users/sam/Desktop/input.docx"));
    for (XWPFParagraph paragraph : document.getParagraphs()) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            text = text.replace("$name", "Sam");
            text = text.replace("$id", "1001");
            run.setText(text);
            System.out.println(text);
            }
        }
    document.write(new FileOutputStream("output.docx"));            
}

我的文字文档包含:

Your Name: $name
Your Id: $id

输出完全是这样的:(

Your Name: $
n
ame
Your Id: 1001

1 个答案:

答案 0 :(得分:0)

我加倍检查了您的代码,这是可行的。我只将setText替换为setText(text,0),因为在我的情况下,文本是重复的。

 XWPFDocument document = new 
 XWPFDocument(OPCPackage.open("/home/tirex/document.docx"));
    for (XWPFParagraph paragraph : document.getParagraphs()) {
        for (XWPFRun run : paragraph.getRuns()) {
            String text = run.getText(0);
            text = text.replace("$name", "Sam");
            text = text.replace("$id", "1001");
            run.setText(text,0);
            System.out.println(text);
        }
    }

文档文件中可能有问题。

顺便说一句。我是您链接中的作者网站,如果代码示例有问题,您只需在注释中写上即可。

相关问题