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

Apache POI 實戰:讀取 Word、PPT、Excel 檔案完整範例

     編輯:Java 程式設計入門

Apache POI 是 Java 處理 Microsoft Office 格式(OLE2 與 OOXML)的標準函式庫。本文提供 POI 讀取 Word (.doc)、PowerPoint (.ppt)、Excel (.xls) 三種舊版二進位格式的完整程式碼範例。

必要依賴

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version> <!-- 或更新版本 -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>3.17</version>
</dependency>

注意:Office 2007+ 格式需改用 poi-ooxml(XWPFDocument、XSSFWorkbook 等類別)。

Word 文件讀取

方式一:一次性抽取全文

public static String readDoc1(InputStream is) throws IOException {
    WordExtractor extractor = new WordExtractor(is);
    return extractor.getText();
}

方式二:逐層解析(區段→段落→文字片段)

public static void readDoc2(InputStream is) throws IOException {
    HWPFDocument doc = new HWPFDocument(is);
    Range range = doc.getRange();
    
    for (int i = 0; i < range.numSections(); i++) {
        Section section = range.getSection(i);
        for (int j = 0; j < section.numParagraphs(); j++) {
            Paragraph para = section.getParagraph(j);
            for (int k = 0; k < para.numCharacterRuns(); k++) {
                CharacterRun run = para.getCharacterRun(k);
                System.out.print(run.text());
            }
        }
    }
}

第二種方式可保留結構資訊,適合需進一步處理格式、樣式的場景。

PowerPoint 簡報讀取

方式一:直接抽取全部文字

public static String readDoc1(InputStream is) throws IOException {
    PowerPointExtractor extractor = new PowerPointExtractor(is);
    return extractor.getText();
}

方式二:逐頁解析(含標題與內文)

public static void readDoc2(InputStream is) throws IOException {
    SlideShow ss = new SlideShow(new HSLFSlideShow(is));
    Slide[] slides = ss.getSlides();
    
    for (Slide slide : slides) {
        // 取得投影片標題
        String title = slide.getTitle();
        System.out.println("標題: " + title);
        
        // 取得所有文字內容
        TextRun[] runs = slide.getTextRuns();
        for (TextRun run : runs) {
            System.out.println(run.getText());
        }
    }
}

Excel 試算表讀取

方式一:一次性抽取全內容

public static String readDoc1(InputStream is) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
    ExcelExtractor extractor = new ExcelExtractor(wb);
    extractor.setFormulasNotResults(false);  // 顯示公式結果而非公式
    extractor.setIncludeSheetNames(true);    // 包含工作表名稱
    return extractor.getText();
}

方式二:逐列逐儲存格處理(計算加權平均)

public static double getAvg(InputStream is) throws IOException {
    HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(is));
    HSSFSheet sheet = wb.getSheetAt(0);  // 取第一個工作表
    
    double molecule = 0.0;
    double denominator = 0.0;
    
    Iterator<Row> rowIter = sheet.rowIterator();
    while (rowIter.hasNext()) {
        HSSFRow row = (HSSFRow) rowIter.next();
        HSSFCell cell1 = row.getCell(4);  // 第 5 欄
        HSSFCell cell2 = row.getCell(5);  // 第 6 欄
        
        // 型別檢查
        if (cell1.getCellType() != HSSFCell.CELL_TYPE_NUMERIC ||
            cell2.getCellType() != HSSFCell.CELL_TYPE_NUMERIC) {
            throw new IllegalStateException("資料型別錯誤,預期數值型別");
        }
        
        denominator += cell2.getNumericCellValue();
        molecule += cell2.getNumericCellValue() * cell1.getNumericCellValue();
    }
    return molecule / denominator;
}

核心類別對照表

檔案類型主要類別提取器適用格式
WordHWPFDocumentWordExtractor.doc (OLE2)
PPTHSLFSlideShow / SlideShowPowerPointExtractor.ppt (OLE2)
ExcelHSSFWorkbookExcelExtractor.xls (OLE2)

實務建議

  • 大檔案建議使用 SAX 風格事件驅動解析(XSSFReader、XLSXReader)避免 OOM
  • .docx/.pptx/.xlsx 請改用 XWPFDocument、XMLSlideShow、XSSFWorkbook
  • 儲存格型別判斷請用 getCellTypeEnum() (POI 3.15+) 取代已棄用常數
  • 日期儲存格需用 DateUtil.isCellDateFormatted() 判斷後再轉換
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved