在 Java 企業級開發中,Excel 數據導入是高頻需求。Apache POI 作為操作 Microsoft Office 文檔的標準庫,提供了 HSSF(處理 .xls)與 XSSF(處理 .xlsx)兩套 API。本文封裝了一個通用的 ExcelReader 工具類,支援文件路徑、FileInputStream、InputStream 多種輸入源,並演示了如何讀取郵編數據作為實戰案例。
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.3</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
String 路徑、FileInputStream、InputStream,覆蓋本地文件、網絡流、資源文件等場景;try-catch-finally 確保流關閉,避免句柄洩漏;public static HSSFSheet readHssfExcel(String path) {
File file = new File(path);
try (FileInputStream is = new FileInputStream(file)) {
HSSFWorkbook wb = new HSSFWorkbook(is);
return wb.getSheetAt(0);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static XSSFSheet readXssfExcel(InputStream is) {
try {
XSSFWorkbook wb = new XSSFWorkbook(is);
return wb.getSheetAt(0);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
注意:XSSFWorkbook 構造函數會消耗輸入流,調用方無需手動關閉(內部已處理),但若傳入 FileInputStream 仍建議外層管理生命週期。
public static void main(String[] args) {
// 從 classpath 讀取 resources/postcode.xlsx
InputStream is = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("postcode.xlsx");
XSSFSheet sheet = readXssfExcel(is);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
if (row == null) continue;
// 假設第1列為數字郵編,第2列為字符串地址
System.out.println("郵編:" + (long) row.getCell(0).getNumericCellValue());
System.out.println("地址:" + row.getCell(1).getStringCellValue());
}
}
ExcelReader 介面,採用策略模式自動判斷格式(WorkbookFactory.create());SXSSF 或 XSSFReader (SAX 事件模型) 避免 OOM;提示:完整代碼已包含包聲明與導入,可直接複製到項目中使用。