tabular-exporter —— 記錄陣列匯出為表格
將任意「物件陣列」轉換成帶樣式的 Excel 或帶 BOM 的 CSV。 零依賴:xlsx 由純 JS 生成(ZIP STORE 法,內建 CRC32),CSV 自帶 UTF-8 BOM。無需
npm install任何套件。
適用場景
- 將擷取 / 介面回傳的結構化資料匯出成可交付的 Excel / CSV
- 後台「匯出」功能、資料報表、資料遷移
- 需要中文不亂碼、帶表頭樣式、凍結首行
提供的函式
| 函式 | 說明 |
|---|---|
exportToExcel(rows, columns, opts?) | 生成帶樣式的 xlsx(Buffer),可選寫入 filePath |
exportToCsv(rows, columns, opts?) | 生成帶 BOM 的 CSV 字串 |
exportTable(rows, columns, opts?) | 統一入口,opts.format = 'xlsx' | 'csv' |
columnsFromKeys(keys, widths?) | 由 key 列表快速產生欄位配置 |
columns 格式如 [{ key, header?, width? }],rows 為物件陣列。
樣式特性:
- 表頭:粗體 + 白字 + 藍底(
4472C4) - 凍結首行
- 斑馬紋(偶數行淺灰底)
- 布林值 →
是/否;陣列 → 換行;物件 → JSON - xlsx 與 Excel / WPS / LibreOffice 相容(標準 OOXML)
用法
import { exportTable, columnsFromKeys } from './scripts/exporter.mjs';
const rows = [
{ title: '無線滑鼠', price: 99.5, inStock: true },
{ title: '機械鍵盤', price: 299, inStock: false },
];
const columns = [
{ key: 'title', header: '標題', width: 40 },
{ key: 'price', header: '價格', width: 12 },
{ key: 'inStock', header: '有貨', width: 8 },
];
// 匯出 xlsx(直接寫入檔案)
exportTable(rows, columns, { format: 'xlsx', filePath: 'out.xlsx', sheetName: '商品' });
// 匯出 csv(回傳字串)
const csv = exportTable(rows, columns, { format: 'csv' });
自測
node scripts/exporter.mjs --selftest