使用 Apache POI 更新 MSWord 文档 [英] Updating an MSWord document with Apache POI

查看:40
本文介绍了使用 Apache POI 更新 MSWord 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Apache POI 更新 Microsoft Word 文档.msword 文档是一个模板,其中包含许多形式为${place.holder}"的占位符,我需要做的就是用特定值替换这些占位符.到目前为止我得到的是

I'm trying to update a Microsoft Word document using Apache POI. The msword document is a template that contains a number of placeholders in the form "${place.holder}" and all I need to do is to replace the holders with specific values. What I've got so far is

private void start() throws FileNotFoundException, IOException {

    POIFSFileSystem fsfilesystem = null;
    HWPFDocument hwpfdoc = null;

    InputStream resourceAsStream =  getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");       
    try {
        fsfilesystem = new POIFSFileSystem(resourceAsStream );
        hwpfdoc = new HWPFDocument(fsfilesystem);
        Range range = hwpfdoc.getRange();

        range.replaceText("${rma.number}","08739");
        range.replaceText("${customer.name}", "Roger Swann");

        FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\updatedTemplate.doc"));
        hwpfdoc.write(fos);
        fos.flush();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

程序运行没有错误.如果我使用十六进制编辑器查看输出文件,我可以看到占位符已被程序替换.但是,当我尝试使用 MSWord 打开文档时,MSWord 崩溃了.

The program runs without errors. If I look in the output file with a Hex editor I can see that the placeholders have been replaced by the program. However, when I try to open the document with MSWord, MSWord crashes.

是否有我遗漏的步骤(一系列步骤),或者我基本上不走运?替换文本的长度与替换文本的长度不同,是否需要调整任何计数器?

Is there a step (series of steps) that I'm missing, or am I basically out of luck with this? Do I need to adjust any counters because the length of the replacement text is not the same as the length of the replaced text?

问候

推荐答案

使用 new FileInputStream() 而不是 getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");

这篇关于使用 Apache POI 更新 MSWord 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆