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