我有一个Microsoft Word 2007/xml .docx文件,我试图使用Apache POI 3.8beta4进行编辑。该文档包含一个表,其中包含以${place形式保存占位符的单元格。我需要换掉的。到目前为止我得到的是;
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();
}
}
问题在于那个单元格。setText("replacement text"}是附加到已经存在的字符串数据上,而不是替换它,所以我最终在完成的文档中得到的是字符串"{place "。持有人}替换文本"。
如何替换文本而不是追加文本?
对
快速修复方法是获取单元格的底层文本运行,并对其进行更改。这有点繁琐,但可以做到。您可能希望调用cell.getBodyElements()
并遍历它们以找到包含文本的内容。然后,更改其上的文本,而不是直接更改单元格
长期的方法是在POI bugzilla中打开一个新bug,并上传一个失败的单元测试。这应该包括您的文件,并显示文本的"替换",然后保存、重新加载和读取。这个问题可以在以后修复
cell.removeParagraph(0);
cell.setText(entrada.getValue());