使用Apache POI更新MSWord文档



我正在尝试使用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();
    }
}

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

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

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

最新更新