首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Apache POI 讀取 Properties 檔並匯出 Excel 完整實作

     編輯:Java 相關知識

依賴引入

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.3.0</version> <!-- .xls (HSSF) -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>5.3.0</version> <!-- .xlsx (XSSF) -->
</dependency>

核心流程

  1. 載入 .properties 檔 → Properties 物件。
  2. 建立 Workbook (HSSF/XSSF) → Sheet → Row → Cell。
  3. 寫入表頭、資料列,可選樣式(標題背景色、凍結窗格、自動欄寬)。
  4. workbook.write(outputStream) 落盤。

完整程式碼

package poi.demo;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.*;

public class PropertiesToExcel {
    public static void main(String[] args) {
        String propsFile = "config.properties";
        String excelFile = "config.xls"; // 或 .xlsx
        export(propsFile, excelFile);
    }

    public static void export(String propsPath, String excelPath) {
        // 1. 讀取 Properties
        Properties props = new Properties();
        try (InputStream in = new FileInputStream(propsPath)) {
            props.load(in);
        } catch (IOException e) {
            throw new RuntimeException("讀取 properties 失敗", e);
        }

        // 2. 建立 Workbook (這裡用 HSSF .xls,若需 .xlsx 改用 XSSFWorkbook)
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("Properties");

        // 3. 樣式:標題列
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.GOLD.getIndex());
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);

        // 4. 寫入表頭
        Row headerRow = sheet.createRow(0);
        Cell hKey = headerRow.createCell(0);
        hKey.setCellValue("Key");
        hKey.setCellStyle(headerStyle);
        Cell hVal = headerRow.createCell(1);
        hVal.setCellValue("Value");
        hVal.setCellStyle(headerStyle);

        // 5. 寫入資料
        int rowNum = 1;
        for (String key : props.stringPropertyNames()) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(key);
            row.createCell(1).setCellValue(props.getProperty(key));
        }

        // 6. 自動欄寬
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);

        // 7. 凍結首列 (可選)
        sheet.createFreezePane(0, 1);

        // 8. 輸出
        try (FileOutputStream fos = new FileOutputStream(excelPath)) {
            wb.write(fos);
            System.out.println("Excel 匯出完成:" + excelPath);
        } catch (IOException e) {
            throw new RuntimeException("寫入 Excel 失敗", e);
        }
    }
}

進階:支援 .xlsx (XSSF)

// 僅需更換 Workbook 實作類,API 完全相容 (ss.usermodel 介面)
Workbook wb = new XSSFWorkbook(); // 需 poi-ooxml 依賴
// 其餘代碼無需修改

大數據量優化 (SXSSF)

超過 10 萬列建議使用 SXSSFWorkbook (串流式,低記憶體):

SXSSFWorkbook wb = new SXSSFWorkbook(100); // 保留 100 行在記憶體,其餘刷入臨時檔
// 使用方式同 XSSF,最後 wb.write(out); wb.dispose(); // 清理臨時檔

常見問題

  • 中文亂碼:確保 properties 檔為 UTF-8 編碼,new FileInputStream 讀取無編碼問題;若為 ISO-8859-1 需 new InputStreamReader(in, "UTF-8")。
  • 日期/數字格式:Properties 全為字串,若需 Excel 原生類型,需自行解析並設定 CellStyle.setDataFormat。
  • 超大欄寬:autoSizeColumn 可能因字型渲染不準,建議手動設定 sheet.setColumnWidth(0, 256 * 30) (單位 1/256 字元寬)。

總結

Apache POI 提供完整的 Excel 讀寫能力。透過 Workbook/Sheet/Row/Cell 階層模型與 CellStyle 樣式系統,可將 Properties、CSV、資料庫查詢結果等結構化資料高品質匯出為 Excel。選擇 HSSF/XSSF/SXSSF 取決於檔案格式與資料量。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved