【发布时间】:2011-09-16 11:21:43
【问题描述】:
我有一个 Microsoft Word 2007/xml .docx 文件,我正在尝试使用 Apache POI 3.8beta4 对其进行编辑。该文档包含一个表格,其中包含一个表格,其中包含我需要替换的 ${place.holder} 形式的占位符。到目前为止,我得到的是;
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("replacement text"} 附加到已经存在的字符串数据而不是替换它,所以我最终在完成的文档中得到的是字符串 "{place.holder}replacement text ”。
如何替换文本而不是追加?
问候
【问题讨论】:
标签: java apache-poi