使用Apache POI更新MSWord文档

时间:2011-09-15 13:05:23

标签: java apache-poi

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

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();
    }

}

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

我是否缺少一步(一系列步骤),或者我基本上没有运气了?我是否需要调整任何计数器,因为替换文本的长度与替换文本的长度不同?

此致

1 个答案:

答案 0 :(得分:0)

使用new FileInputStream()代替getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");