2011-09-16 84 views
4

我有一个Microsoft Word 2007/xml .docx文件,我试图使用Apache POI 3.8beta4进行编辑。除了其他内容之外,该文档还包含一个表格,其中包含需要替换的格式为$ {place.holder}的占位符的单元格。到目前为止我所拥有的是;使用Apache POI更新Microsoft Word 2007/xml .docx文件会附加文本而不是替换?

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(“替换文本”}被追加到已经存在的,而不是取代它的字符串数据,所以我完成的文档中结束了是字符串“{地方。吸}替换文本”。

如何替换文本而不是附加给它?

问候

回答

1

速战速决是让电池的基础文本运行,并改变这种状况。这是有点烦琐,但可以完成,你可能想打cell.getBodyElements()并遍历它们以找到文本中的内容。然后,更改文本,而不是尝试直接更改单元格

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

+0

是的,只要我使用setText(String,int)方法,就可以继续使用XWPFRun级别。使用直接setText(String)追加。 – user497087

+0

你最好报告一个bug! :) – Gagravarr

1
cell.removeParagraph(0); 
cell.setText(entrada.getValue()); 
+1

我不明白 - 什么是“entrada”变量? –

相关问题