<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>
.properties 檔 → Properties 物件。Workbook (HSSF/XSSF) → Sheet → Row → Cell。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);
}
}
}
// 僅需更換 Workbook 實作類,API 完全相容 (ss.usermodel 介面)
Workbook wb = new XSSFWorkbook(); // 需 poi-ooxml 依賴
// 其餘代碼無需修改
超過 10 萬列建議使用 SXSSFWorkbook (串流式,低記憶體):
SXSSFWorkbook wb = new SXSSFWorkbook(100); // 保留 100 行在記憶體,其餘刷入臨時檔
// 使用方式同 XSSF,最後 wb.write(out); wb.dispose(); // 清理臨時檔
new FileInputStream 讀取無編碼問題;若為 ISO-8859-1 需 new InputStreamReader(in, "UTF-8")。CellStyle.setDataFormat。autoSizeColumn 可能因字型渲染不準,建議手動設定 sheet.setColumnWidth(0, 256 * 30) (單位 1/256 字元寬)。Apache POI 提供完整的 Excel 讀寫能力。透過 Workbook/Sheet/Row/Cell 階層模型與 CellStyle 樣式系統,可將 Properties、CSV、資料庫查詢結果等結構化資料高品質匯出為 Excel。選擇 HSSF/XSSF/SXSSF 取決於檔案格式與資料量。