2016-12-01 106 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)將其保存回磁盤。

相關問題