萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Excel 教學 >> Excel 綜合

Apache POI 設定 Excel 儲存格樣式完整範例:背景、邊框、置中、字型、欄寬、自動換行、合併儲存格

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)

📋 完整範例:建立「月報表」 (HSSF .xls 格式)

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;
    }
}

⚠️ 避坑指南

  • HSSF (.xls) vs XSSF (.xlsx): 類名前綴不同 (HSSF/XSSF),API 大同小異,建議用 Workbook 介面多型撰寫。
  • 樣式物件重用: 同一 Workbook 內相同樣式只建立一次,重複 createCellStyle() 會導致樣式表爆滿 (上限 64k)。
  • 字型相容性: 伺服器若無指定字體,輸出 PDF/列印會替換。建議內嵌字體或用標準字體 (Arial, 微軟正黑體)。
  • 大數據量: 使用 SXSSFWorkbook (串流模式,僅支援 .xlsx) 避免 OOM。
  • 日期/數字格式: 用 DataFormat 設定 style.setDataFormat(fmt.getFormat("yyyy/mm/dd"))。

💡 進階延伸:

  • 條件格式: sheet.getSheetConditionalFormatting().addConditionalFormatting(...)。
  • 資料驗證 (下拉選單): DataValidationHelper + DataValidationConstraint。
  • 圖片插入: Drawing patriarch = sheet.createDrawingPatriarch(); + ClientAnchor。
  • 樞紐分析表: POI 4.0+ 支援建立/重新整理樞紐分析表。

掌握 POI 樣式 API,Java 產出專業級 Excel 報表不再是夢!

copyright © 萬盛學電腦網 all rights reserved