2016-12-01 114 views
3

我想使用Java以doc格式和docx格式文件使用Java查找和替换文本。如何在word文档中查找和替换文本doc和docx

我试过了:我尝试读取这些文件作为文本文件,但没有成功。

我不知道如何继续或尝试什么,任何人都可以给我方向?

+1

文件格式是不一样的文本格式。告诉我们你试过的东西,请附上[MCVE],阅读[FAQ]。 – t0mm13b

+1

尝试apache poi字来阅读文件 – XtremeBaumer

回答

1

我希望这会解决你的问题我的朋友。我写它的docx,以搜索和替换使用apache.poi 我建议你阅读完整的Apache POI的详细

public class Find_Replace_DOCX { 

    public static void main(String args[]) throws IOException, 
     InvalidFormatException, 
     org.apache.poi.openxml4j.exceptions.InvalidFormatException { 
     try { 

     /** 
     * if uploaded doc then use HWPF else if uploaded Docx file use 
     * XWPFDocument 
     */ 
     XWPFDocument doc = new XWPFDocument(
     OPCPackage.open("d:\\1\\rpt.docx")); 
     for (XWPFParagraph p : doc.getParagraphs()) { 
     List<XWPFRun> runs = p.getRuns(); 
     if (runs != null) { 
     for (XWPFRun r : runs) { 
      String text = r.getText(0); 
      if (text != null && text.contains("$$key$$")) { 
      text = text.replace("$$key$$", "ABCD");//your content 
      r.setText(text, 0); 
      } 
     } 
     } 
     } 

     for (XWPFTable tbl : doc.getTables()) { 
     for (XWPFTableRow row : tbl.getRows()) { 
     for (XWPFTableCell cell : row.getTableCells()) { 
      for (XWPFParagraph p : cell.getParagraphs()) { 
      for (XWPFRun r : p.getRuns()) { 
      String text = r.getText(0); 
      if (text != null && text.contains("$$key$$")) { 
      text = text.replace("$$key$$", "abcd"); 
      r.setText(text, 0); 
      } 
      } 
      } 
     } 
     } 
     } 

     doc.write(new FileOutputStream("d:\\1\\output.docx")); 
     } finally { 

     } 

    } 

    } 
+0

它完全按照想要的完美工作...超棒。 –

+1

这需要注释或解释。但我喜欢这个缩进! – AxelH

+0

这是来自https://poi.apache.org/的知识。我强烈建议阅读之前。 –

4

这些文档格式是复杂的对象,你几乎肯定不想试图解析你自己。我会强烈建议您看看apache poi库 - 这些库具有加载和保存doc和docx格式的功能,并且可以访问和修改文件的内容。

他们是有据可查,开源,目前维护和免费提供。

总之,使用这些库来:a)加载文件b)以编程方式浏览文件的内容,并根据需要修改它(即执行搜索和替换)并c)将其保存回磁盘。

相关问题