【问题标题】:Updating a Microsoft Word 2007/xml .docx file with Apache POI appends text rather than replaces?使用 Apache POI 更新 Microsoft Word 2007/xml .docx 文件会附加文本而不是替换?
【发布时间】: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


    【解决方案1】:

    快速解决方法是获取单元格的底层文本运行,然后更改它。这有点繁琐,但可以做到。您可能想调用 cell.getBodyElements() 并遍历它们以找到包含您的文本的内容。然后,更改其上的文本,而不是尝试直接更改单元格

    长期的做法是在 POI bugzilla 中打开一个新错误,然后上传一个失败的单元测试。这可能应该包括您的文件,并显示文本的“替换”,然后是保存、重新加载和读取。这个问题可以稍后解决

    【讨论】:

    • 是的,只要我使用 setText(String,int) 方法,就可以进入 XWPFRun 级别。使用直接的 setText(String) 追加。
    • 你最好报告一个错误! :)
    【解决方案2】:
    cell.removeParagraph(0);
    cell.setText(entrada.getValue());
    

    【讨论】:

    • 我不明白 - 什么是“entrada”变量?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    • 2020-02-27
    相关资源
    最近更新 更多