如何查找和替换word文件doc和docx中的文本

ROH*_*R A 6 java

我想使用Java以doc格式和docx格式文件查找和替换文本.

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

我不知道如何继续或者还有什么可以尝试,任何人都可以指导我吗?

Kis*_*nCS 5

我希望这能解决您的问题,我的朋友。我已经为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 {

      }

     }

    }
Run Code Online (Sandbox Code Playgroud)