开发者

Updating a Microsoft Word 2007/xml .docx file with Apache POI appends text rather than replaces?

I have a Microsoft Word 2007/xml .docx file that I am trying to edit using Apache POI 3.8beta4. The document contains, among other things, a table that contains cells that hold place holders in the form ${place.holder} that I need to replace. What I've got so far is;

    InputStream resourceAsStream =  getClass().getResourceAsStream("/path/to/templates/rma.docx");       
    try {
        XWPFDocument xwpfdoc = new XWPFDocument(resourceAsStream); 

        FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\newTemplate.docx"));

        for (XWPFTable table : x开发者_C百科wpfdoc.getTables()) {

             for (XWPFTableRow row : table.getRows()) {

                 for (XWPFTableCell cell : row.getTableCells()) {

                     String data = cell.getText();

                     if (data.contains("${rma.number}")) {
                         cell.setText("08739");
                     }

                     if (data.contains("${customer.name}")) {
                         cell.setText("Roger Swann");
                     }
                 }
             }
        }
        xwpfdoc.write(fos);
        fos.flush();
        fos.close();

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

    } 

The problem is that cell.setText("replacement text"} is appending to the string data already present instead of replacing it, so what I end up with in the finished document is the string "{place.holder}replacement text".

How do I replace the text rather than append to it?

Regards


The quick fix is to get the underlying text run of the cell, and change that. It's a bit fiddly, but it can be done. You'd likely want to call cell.getBodyElements() and iterate through them to find the thing with your text in. Then, change the text on that, rather than trying to change the cell directly

The longer term one is to open a new bug in the POI bugzilla, and upload a failing unit test. This should probably include your file, and show the "replacement" of the text, followed by saving, reloading, and reading. The issue can then later be fixed


cell.removeParagraph(0);
cell.setText(entrada.getValue());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜