首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Apache POI 讀取 Office 檔案完整教學:Word、PPT、Excel (HSSF/XSSF)

     編輯:Java 相關知識

前言

Apache POI 是 Java 操作 Microsoft Office 格式的標準庫,支援舊版 OLE2 (.doc, .xls, .ppt) 與新版 OOXML (.docx, .xlsx, .pptx)。本文示範使用 POI 3.17+ 讀取三種檔案的文字內容與結構化資料。

Maven 依賴

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>5.3.0</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.3.0</version>
</dependency>

1. 讀取 Word (.doc / .docx)


// .doc (HWPF)
try (FileInputStream fis = new FileInputStream("test.doc")) {
    HWPFDocument doc = new HWPFDocument(fis);
    WordExtractor extractor = new WordExtractor(doc);
    System.out.println(extractor.getText()); // 全文
}

// .docx (XWPF) - 同理使用 XWPFDocument

2. 讀取 PowerPoint (.ppt / .pptx)


// .ppt (HSLF)
try (FileInputStream fis = new FileInputStream("test.ppt")) {
    SlideShow ss = new SlideShow(new HSLFSlideShow(fis));
    for (Slide slide : ss.getSlides()) {
        System.out.println("標題: " + slide.getTitle());
        for (TextRun run : slide.getTextRuns()) {
            System.out.println(run.getText());
        }
    }
}

// .pptx (XSLF) 使用 XMLSlideShow

3. 讀取 Excel (.xls / .xlsx)


// .xls (HSSF)
try (FileInputStream fis = new FileInputStream("test.xls")) {
    HSSFWorkbook wb = new HSSFWorkbook(fis);
    HSSFSheet sheet = wb.getSheetAt(0);
    for (Row row : sheet) {
        for (Cell cell : row) {
            System.out.print(cell.toString() + "\t");
        }
        System.out.println();
    }
}

// .xlsx (XSSF) 類別名稱改為 XSSFWorkbook 等,API 相同

進階技巧

  • 使用 WorkbookFactory.create(inputStream) 自動偵測 .xls/.xlsx。
  • 大檔案改用 SXSSFWorkbook (串流寫入) 或 XSSFReader (SAX 解析) 降低記憶體。
  • 公式計算需呼叫 FormulaEvaluator。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved