我有一个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