我有一个 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 ”。
如何替换文本而不是追加文本?
问候
最佳答案
快速修复是获取单元格的底层文本并更改它。这有点繁琐,但可以做到。您可能想要调用 cell.getBodyElements()
并遍历它们以找到包含您的文本的内容。然后,更改上面的文本,而不是尝试直接更改单元格
长期的方法是在 POI bugzilla 中打开一个新错误,并上传一个失败的单元测试。这可能应该包括您的文件,并显示文本的“替换”,然后保存、重新加载和阅读。稍后可以修复该问题
关于java - 使用 Apache POI 更新 Microsoft Word 2007/xml .docx 文件会附加文本而不是替换文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7443944/