Updating a Microsoft Word 2007 / xml.docx file with Apache POI adds text instead of replacing?

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 containing cells that hold place holders in the form of $ {place.holder}, which I need to replace. What I still know

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 : xwpfdoc.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") adds to the existing string data instead of replacing it, so ultimately in the final document is the string "{place.holder} replacement text".

How to replace text, and not add to it?

Hello

+4
source share
2 answers

A quick fix is โ€‹โ€‹to get the base text mileage of the cell and change it. This is a bit hesitant, but it can be done. You most likely want to call cell.getBodyElements() and cut through them to find an item with text. Then change the text on it, and don't try to change the cell directly

In the long run, you need to open a new bug in the bugzilla POI and load the unit test failure. This should probably include your file and show a โ€œreplacementโ€ of text, and then save, reload and read. Then the problem can be fixed.

+1
source
 cell.removeParagraph(0); cell.setText(entrada.getValue()); 
+1
source

All Articles