Java 用ApachePOI更新MicrosoftWord2007/xml.docx文件会附加文本而不是替换?

Java 用ApachePOI更新MicrosoftWord2007/xml.docx文件会附加文本而不是替换?,java,apache-poi,Java,Apache Poi,我有一个Microsoft Word 2007/xml.docx文件,我正试图使用ApachePOI3.8beta4编辑该文件。除其他外,该文档包含一个表,其中包含以${place.holder}形式保存占位符的单元格,我需要替换这些占位符。到目前为止,我得到的是 InputStream resourceAsStream = getClass().getResourceAsStream("/path/to/templates/rma.docx"); try {

我有一个Microsoft Word 2007/xml.docx文件,我正试图使用ApachePOI3.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(“替换文本”}附加到已经存在的字符串数据,而不是替换它,因此在完成的文档中,我得到的是字符串“{place.holder}替换文本”

如何替换文本而不是附加到文本


关于

快速修复方法是运行单元格的底层文本,并对其进行更改。这有点麻烦,但可以完成。您可能需要调用
cell.getBodyElements()
并对其进行迭代,以找到包含文本的内容。然后,更改其中的文本,而不是直接尝试更改单元格


长期的做法是在POI bugzilla中打开一个新的bug,并上传一个失败的单元测试。这可能包括您的文件,并显示文本的“替换”,然后保存、重新加载和读取。如果我使用setText(String,int),这个问题可以在以后得到修复

Yes,转到XWPFRun级别工作,前提是我使用setText(String,int)方法。使用直接的setText(字符串)附件。您最好报告一个错误!:)我不明白-什么是“entrada”变量?
cell.removeParagraph(0);
cell.setText(entrada.getValue());