开发者

Updating an MSWord document with Apache POI

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}"开发者_如何学Go,"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();
    }

}

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?

Regards


use new FileInputStream() instead of getClass().getResourceAsStream("/path/to/document/templates/RMA FORM.doc");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜