Apache POI 是 Java 操作 Excel (.xls/.xlsx) 的標準庫。本文整理常用儲存格樣式設定 API,並附完整可執行範例 (建立月報表),涵蓋背景色、邊框、對齊、字型、欄寬、自動換行、合併儲存格。
Workbook (HSSFWorkbook/XSSFWorkbook)
└─ Sheet (createSheet)
└─ Row (createRow)
└─ Cell (createCell)
└─ CellStyle (createCellStyle) ← 樣式核心
├─ Fill (背景)
├─ Border (邊框)
├─ Alignment (對齊)
└─ Font (字型) ← 需建立 Font 物件再 setFont
| 需求 | API | 備註 |
|---|---|---|
| 背景色 | style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index)style.setFillPattern(FillPatternType.SOLID_FOREGROUND) | 建議用 IndexedColors 列舉避免魔術數字 |
| 邊框 (四邊細線) | style.setBorderBottom(BorderStyle.THIN)style.setBorderTop(BorderStyle.THIN)style.setBorderLeft(BorderStyle.THIN)style.setBorderRight(BorderStyle.THIN) | 可分別設定顏色 setBottomBorderColor |
| 水平置中 | style.setAlignment(HorizontalAlignment.CENTER) | |
| 垂直置中 | style.setVerticalAlignment(VerticalAlignment.CENTER) | |
| 字型 | Font font = wb.createFont();font.setFontName("微軟正黑體");font.setFontHeightInPoints((short)12);font.setBold(true);style.setFont(font); | 字型需系統安裝,建議用通用字體 |
| 欄寬 | sheet.setColumnWidth(colIndex, width * 256) | 單位為 1/256 字元寬度,實際像素約 width*256 |
| 自動換行 | style.setWrapText(true) | 需搭配行高自動調整 row.setHeightInPoints(-1) |
| 合併儲存格 | sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)) | 參數:起始列、終止列、起始欄、終止欄 (0-based) |
package cn.com.util;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.*;
import java.io.FileOutputStream;
public class CreateMonthlyReport {
public static void main(String[] args) throws Exception {
// 1. 建立工作簿與工作表
Workbook wb = new HSSFWorkbook(); // .xls 格式;若需 .xlsx 用 new XSSFWorkbook()
Sheet sheet = wb.createSheet("月報表");
// 2. 共用樣式:標題、表頭、內文
CellStyle titleStyle = createStyle(wb, (short)16, "標楷體", true, HorizontalAlignment.CENTER, VerticalAlignment.CENTER, IndexedColors.BLUE_GREY.index);
CellStyle headerStyle = createStyle(wb, (short)12, "微軟正黑體", true, HorizontalAlignment.CENTER, VerticalAlignment.CENTER, IndexedColors.GREY_25_PERCENT.index);
CellStyle bodyStyle = createStyle(wb, (short)11, "微軟正黑體", false, HorizontalAlignment.CENTER, VerticalAlignment.CENTER, IndexedColors.WHITE.index);
bodyStyle.setWrapText(true); // 內文自動換行
// 3. 設定欄寬
sheet.setColumnWidth(0, 12 * 256);
sheet.setColumnWidth(1, 30 * 256);
sheet.setColumnWidth(2, 20 * 256);
// ... 其他欄寬
// 4. 第一列:標題跨欄合併
Row row = sheet.createRow(0);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 11));
Cell cell = row.createCell(0);
cell.setCellValue("北京億卡聯科技發展有限公司小區門禁維修月報表");
cell.setCellStyle(titleStyle);
// 5. 第二列:時間區間、單位
row = sheet.createRow(1);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 3, 6));
cell = row.createCell(3); cell.setCellValue("時間區間:2024/01/01 ~ 2024/01/31"); cell.setCellStyle(headerStyle);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 9, 10));
cell = row.createCell(9); cell.setCellValue("單位:元"); cell.setCellStyle(headerStyle);
// 6. 第三列:區塊標題
row = sheet.createRow(2);
cell = row.createCell(0); cell.setCellValue("一、"); cell.setCellStyle(bodyStyle);
cell = row.createCell(1); cell.setCellValue("基本資料"); cell.setCellStyle(bodyStyle);
// 7. 後續列:標籤+值,部分合併
String[][] data = {
{"小區名稱:", "綠園小區", 2, 11},
{"座落地點:", "北京市朝陽區xxx路", 2, 11},
{"建成年月:", "2010年5月", 2, 4, "聯絡人", "王大明", 6, 8, "電話", "010-12345678", 10, 11}
};
int r = 3;
for (String[] d : data) {
row = sheet.createRow(r++);
for (int i = 0; i < d.length; i += 3) {
cell = row.createCell(Integer.parseInt(d[i+2])); // 簡化示意,實際應解析
cell.setCellValue(d[i+1]);
cell.setCellStyle(bodyStyle);
if (i+3 < d.length && d[i+3].matches("\\d+")) { // 有合併欄位
sheet.addMergedRegion(new CellRangeAddress(r-1, r-1, Integer.parseInt(d[i+2]), Integer.parseInt(d[i+3])));
}
}
}
// 8. 輸出檔案
try (FileOutputStream fos = new FileOutputStream("d:/monthly_report.xls")) {
wb.write(fos);
}
wb.close();
System.out.println("報表產生完成!");
}
// 樣式工廠方法
private static CellStyle createStyle(Workbook wb, short fontSize, String fontName, boolean bold,
HorizontalAlignment halign, VerticalAlignment valign, short bgColorIndex) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
font.setFontName(fontName);
font.setFontHeightInPoints(fontSize);
font.setBold(bold);
style.setFont(font);
style.setAlignment(halign);
style.setVerticalAlignment(valign);
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
if (bgColorIndex != IndexedColors.WHITE.index) {
style.setFillForegroundColor(bgColorIndex);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
return style;
}
}
Workbook 介面多型撰寫。createCellStyle() 會導致樣式表爆滿 (上限 64k)。SXSSFWorkbook (串流模式,僅支援 .xlsx) 避免 OOM。DataFormat 設定 style.setDataFormat(fmt.getFormat("yyyy/mm/dd"))。💡 進階延伸:
sheet.getSheetConditionalFormatting().addConditionalFormatting(...)。DataValidationHelper + DataValidationConstraint。Drawing patriarch = sheet.createDrawingPatriarch(); + ClientAnchor。掌握 POI 樣式 API,Java 產出專業級 Excel 報表不再是夢!