JXL (Java Excel API) 是早期操作 Excel 97-2003 格式 的純 Java 庫,雖已停止維護 (最後版本 2009),但在維護舊系統、簡單 .xls 需求下仍有使用。本例演示寫入格式化儲存格 (日期、數字、字串) 及讀取指定行/儲存格資料。
public void write() {
WritableWorkbook workbook = Workbook.createWorkbook(new File("myfile.xls"));
WritableSheet sheet = workbook.createSheet("午餐記錄", 0);
// 表頭
sheet.addCell(new Label(0, 0, "時間"));
sheet.addCell(new Label(1, 0, "姓名"));
sheet.addCell(new Label(2, 0, "午餐標準"));
sheet.addCell(new Label(3, 0, "實際費用"));
// 格式化日期
DateFormat df = new DateFormat("yyyy-dd-MM hh:mm:ss");
WritableCellFormat wcfDF = new WritableCellFormat(df);
sheet.addCell(new DateTime(0, 1, new Date(), wcfDF));
// 普通字串
sheet.addCell(new Label(1, 1, "riverwind"));
// 格式化數字 (保留兩位小數)
NumberFormat nf = new NumberFormat("#.##");
WritableCellFormat wcfN = new WritableCellFormat(nf);
sheet.addCell(new Number(2, 1, 13.1415926, wcfN));
sheet.addCell(new Number(3, 1, 10.50001, wcfN));
workbook.write(); workbook.close(); // 必須 write() 後 close()
}
// 讀取指定儲存格
public String read(int col, int row) {
Cell a2 = sheet.getCell(col, row);
return a2.getContents();
}
// 讀取整行
public String[] readLine(int row) {
int colnum = sheet.getColumns();
String[] rest = new String[colnum];
for (int i = 0; i < colnum; i++) {
String sTemp = read(i, row);
if (sTemp != null) rest[i] = sTemp;
}
return rest;
}
| 限制 | 影響 | 替代方案 |
|---|---|---|
| 僅支援 .xls (BIFF8) | 無法讀寫 .xlsx (OOXML) | Apache POI (支援 .xls/.xlsx, 功能最全, 社群活躍) |
| 不支援圖表、樞紐分析表、巨集、條件格式等高級功能 | 複雜報表無法生成 | POI / EasyExcel (阿里, 低記憶體串流讀寫) |
| 大檔案記憶體佔用高 | 易 OOM | EasyExcel / POI SXSSF (串流) |
| 中文檔名/儲存格編碼偶發問題 | 亂碼風險 | POI 完善支援 UTF-8 |
| 停止維護 15 年 | 安全漏洞、JDK 相容性風險 | 強烈建議遷移至 POI 或 EasyExcel |
// JXL // POI (HSSF .xls / XSSF .xlsx)
Workbook.createWorkbook(file) // new HSSFWorkbook() / new XSSFWorkbook()
workbook.createSheet(name, idx) // workbook.createSheet(name)
sheet.addCell(new Label(c,r,v)) // row.createCell(c).setCellValue(v)
DateTime + DateFormat // cell.setCellValue(date) + CellStyle.setDataFormat(format)
Number + NumberFormat // cell.setCellValue(num) + CellStyle.setDataFormat("#.##")
workbook.write(); workbook.close() // workbook.write(out); workbook.close(); (需 FileOutputStream)