Apache POI Word - 文字提取



本章介紹如何使用 Java 從 Word 文件中提取簡單的文字資料。如果你希望從 Word 文件中提取元資料,請使用 Apache Tika。

對於 .docx 檔案,我們使用 org.apache.poi.xwpf.extractor.XPFFWordExtractor 類,用於從 Word 檔案中提取並返回簡單資料。類似地,我們有不同的方法用於從 Word 檔案中提取標題、腳註、表格資料等。

以下程式碼展示如何從 Word 檔案中提取簡單的文字,−

import java.io.FileInputStream;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class WordExtractor {
   public static void main(String[] args)throws Exception {
      XWPFDocument docx = new XWPFDocument(new FileInputStream("createparagraph.docx"));
      
      //using XWPFWordExtractor Class
      XWPFWordExtractor we = new XWPFWordExtractor(docx);
      System.out.println(we.getText());
   }
}

將上述程式碼另存為 WordExtractor.java。從命令提示符中對其進行編譯並執行,如下所示:−

$javac WordExtractor.java
$java WordExtractor

它將生成以下輸出:

At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning purpose
in the domains of Academics, Information Technology, Management and Computer Programming Languages.
廣告