使用Apache POI更新MSWord文档

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

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崩溃了。

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

问候

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