核心流程
- 建立
Workbook:Workbook wb = WorkbookFactory.create(new File("data.xlsx"));(支援 .xls/.xlsx)。
- 遍歷
Sheet → Row → Cell,依條件篩選。
- 使用
BufferedWriter 寫入文字檔,自訂格式(如 CSV、固定寬度、JSON Lines)。
範例代碼
try (Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
Cell c0 = row.getCell(0);
if (c0 != null && c0.getStringCellValue().startsWith("A")) {
String line = String.format("%-10s %-20s %5.2f",
c0.getStringCellValue(),
row.getCell(1).getStringCellValue(),
row.getCell(2).getNumericCellValue());
bw.write(line);
bw.newLine();
}
}
}
注意事項
- 大檔案使用
SXSSFWorkbook(串流式)避免 OOM。
- 日期儲存格需用
DateUtil.isCellDateFormatted(cell) 判斷並格式化。
- 關閉資源請用 try-with-resources 確保釋放。