JXL 是輕量級 Excel 操作庫,適合 .xls 格式的基礎讀寫。本文展示讀取工作簿、遍歷 Sheet/行/單元格的標準代碼模板。
public static void readExcel(String path) {
try {
Workbook book = Workbook.getWorkbook(new File(path));
Sheet sheet = book.getSheet(0); // 首個 Sheet
int rows = sheet.getRows();
for (int i = 1; i < rows; i++) { // 從第 1 行開始(跳過標題)
String col1 = sheet.getCell(0, i).getContents();
String col2 = sheet.getCell(1, i).getContents();
String col3 = sheet.getCell(2, i).getContents();
System.out.printf("用戶名:%s | 密碼:%s | 真實名稱:%s%n", col1, col2, col3);
}
book.close(); // 必須關閉釋放資源
} catch (BiffException | IOException e) {
e.printStackTrace();
}
}
public static void writeExcel(String path, List<String[]> data) {
try {
WritableWorkbook book = Workbook.createWorkbook(new File(path));
WritableSheet sheet = book.createSheet("Sheet1", 0);
// 寫入標題
sheet.addCell(new Label(0, 0, "用戶名"));
sheet.addCell(new Label(1, 0, "密碼"));
sheet.addCell(new Label(2, 0, "真實名稱"));
// 寫入數據
for (int i = 0; i < data.size(); i++) {
String[] row = data.get(i);
sheet.addCell(new Label(0, i+1, row[0]));
sheet.addCell(new Label(1, i+1, row[1]));
sheet.addCell(new Label(2, i+1, row[2]));
}
book.write();
book.close();
} catch (IOException | WriteException e) {
e.printStackTrace();
}
}
Label:字符串Number:數值DateTime:日期時間Boolean:布爾值JXL 已停止維護,不支援 .xlsx。新項目建議直接使用 Apache POI(支援 .xls/.xlsx、流式 SXSSF、樣式豐富)。遷移重點:Workbook→WorkbookFactory、Label→Cell、getContents()→getStringCellValue() 等。