我有一個Microsoft Word 2007/xml .docx文件,我試圖使用Apache POI 3.8beta4進行編輯。除了其他內容之外,該文檔還包含一個表格,其中包含需要替換的格式爲$ {place.holder}的佔位符的單元格。到目前爲止我所擁有的是;使用Apache POI更新Microsoft Word 2007/xml .docx文件會附加文本而不是替換?
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();
}
}
的問題是,cell.setText(「替換文本」}被追加到已經存在的,而不是取代它的字符串數據,所以我完成的文檔中結束了是字符串「{地方。吸}替換文本」。
如何替換文本而不是附加給它?
問候
是的,只要我使用setText(String,int)方法,就可以繼續使用XWPFRun級別。使用直接setText(String)追加。 – user497087
你最好報告一個bug! :) – Gagravarr