JXL (Java Excel API) 是純 Java 實現的 Excel 操作庫,無需依賴 Microsoft Office 即可在 Linux/Unix 伺服器端生成 .xls 格式報表,極適合 Web 應用的後端匯出功能。本文詳細示範從儲存格樣式定義、表頭表體渲染到檔案輸出的完整流程。
package com.yonyou.test;
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.format.*;
import jxl.write.*;
public class JxlTable {
private static final JxlTable INSTANCE = new JxlTable();
public static JxlTable getInstance() { return INSTANCE; }
private JxlTable() {}
public boolean createTable(String header, String[] body, String filePath) {
WritableWorkbook book = null;
try {
book = Workbook.createWorkbook(new File(filePath));
WritableSheet sheet = book.createSheet("報表", 0);
sheet.setColumnView(1, 5);
sheet.getSettings().setShowGridLines(false);
// 表頭處理
String[] headers = header.split(",");
for (int i = 0; i < headers.length; i++) {
Label label = new Label(1 + i, 1, headers[i], getHeaderCellStyle());
sheet.addCell(label);
}
// 表體處理
for (int row = 0; row < body.length; row++) {
String[] cells = body[row].split(",");
for (int col = 0; col < cells.length; col++) {
WritableCellFormat style = getBodyCellStyle();
if (col == 0 || col == cells.length - 1) {
style.setAlignment(Alignment.CENTRE);
}
Label label = new Label(1 + col, 2 + row, cells[col], style);
sheet.addCell(label);
}
}
book.write();
return true;
} catch (IOException | RowsExceededException | WriteException e) {
e.printStackTrace();
return false;
} finally {
if (book != null) {
try { book.close(); } catch (Exception ignored) {}
}
}
}
private WritableCellFormat getHeaderCellStyle() {
WritableFont font = new WritableFont(WritableFont.createFont("微軟正黑體"), 10, WritableFont.BOLD);
WritableCellFormat format = new WritableCellFormat(font);
try {
format.setBackground(Colour.YELLOW);
format.setBorder(Border.ALL, BorderLineStyle.THICK, Colour.BLACK);
format.setAlignment(Alignment.CENTRE);
} catch (WriteException e) {
e.printStackTrace();
}
return format;
}
private WritableCellFormat getBodyCellStyle() {
WritableFont font = new WritableFont(WritableFont.createFont("微軟正黑體"), 10);
WritableCellFormat format = new WritableCellFormat(font);
try {
format.setBackground(Colour.WHITE);
format.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
} catch (WriteException e) {
e.printStackTrace();
}
return format;
}
public static void main(String[] args) {
String header = "編號,姓名,性別,年齡";
String[] body = {
"1,歐陽鋒,男,68",
"2,黃藥師,男,67",
"3,洪七公,男,70",
"4,郭靖,男,32"
};
JxlTable.getInstance().createTable(header, body, "e:/test.xls");
}
}
| 操作 | 方法 | 說明 |
|---|---|---|
| 建立 Workbook | Workbook.getWorkbook(File/InputStream) | 支援檔案與串流兩種來源 |
| 獲取工作表 | wb.getSheet(0) / wb.getSheets() | 索引或取得全部 Sheet 陣列 |
| 讀取儲存格 | sheet.getCell(col, row).getContents() | 取得字串值,另可用 getType() 判斷型別 |
| 關閉資源 | wb.close() | 釋放記憶體,大量讀取時務必呼叫 |
getName():取得工作表名稱getColumns() / getRows():取得總欄數/總列數getColumn(index) / getRow(index):取得整欄/整列儲存格陣列JXL 僅支援舊版 .xls 格式(BIFF8),且已停止維護。新專案建議改用 Apache POI(支援 .xlsx、功能更豐富)或 EasyExcel(記憶體效能更佳),僅在維護舊系統時續用 JXL。