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
source share