260205_01_ENH: 페이지 별 엑셀 다운로드 적용
This commit is contained in:
@@ -174,7 +174,7 @@ type Opts = {
|
||||
/** 기본: ["사례수", "gap"] 제외 */
|
||||
excludeRowLabels?: string[];
|
||||
/** 기본: (y) => `${y}년` */
|
||||
yearLabel?: (y: number) => string;
|
||||
yearLabel?: (y: string) => string;
|
||||
/** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */
|
||||
splitStackByYear?: boolean;
|
||||
};
|
||||
@@ -186,7 +186,7 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
|
||||
splitStackByYear = false,
|
||||
} = opts;
|
||||
|
||||
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
|
||||
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
|
||||
|
||||
// rowLabel 순서: 첫 연도 기준으로 고정(없으면 전체 unique)
|
||||
const baseYear = years[0];
|
||||
@@ -203,7 +203,7 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
|
||||
);
|
||||
|
||||
// 빠른 조회용: year -> (rowLabel -> total)
|
||||
const map = new Map<number, Map<string, number>>();
|
||||
const map = new Map<string, Map<string, number>>();
|
||||
for (const y of years) map.set(y, new Map());
|
||||
for (const r of rows) {
|
||||
if (excludeRowLabels.includes(r.rowLabel)) continue;
|
||||
@@ -229,7 +229,7 @@ export function buildRowLabelSeriesChartData(
|
||||
yearLabel = (y) => `${y}년`,
|
||||
} = opts;
|
||||
|
||||
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
|
||||
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
|
||||
const categories = years.map(yearLabel);
|
||||
|
||||
const baseYear = years[0];
|
||||
@@ -246,7 +246,7 @@ export function buildRowLabelSeriesChartData(
|
||||
);
|
||||
|
||||
// (year -> (rowLabel -> total)) 맵
|
||||
const valueMap = new Map<number, Map<string, number>>();
|
||||
const valueMap = new Map<string, Map<string, number>>();
|
||||
for (const y of years) valueMap.set(y, new Map());
|
||||
|
||||
for (const r of rows) {
|
||||
@@ -270,14 +270,14 @@ export const buildGapRow = (
|
||||
baseRowLabel: string,
|
||||
gapRowLabel = "gap"
|
||||
): ServerBannerRow | null => {
|
||||
const prev = rows.find(r => r.year === prevYear && r.rowLabel === baseRowLabel);
|
||||
const cur = rows.find(r => r.year === curYear && r.rowLabel === baseRowLabel);
|
||||
const prev = rows.find(r => Number(r.year) === prevYear && r.rowLabel === baseRowLabel);
|
||||
const cur = rows.find(r => Number(r.year) === curYear && r.rowLabel === baseRowLabel);
|
||||
if (!prev || !cur) return null;
|
||||
|
||||
const gap: ServerBannerRow = {
|
||||
year: curYear,
|
||||
year: String(curYear),
|
||||
rowLabel: gapRowLabel,
|
||||
total: (typeof cur.total === "number" ? cur.total : 0) - (typeof prev.total === "number" ? prev.total : 0),
|
||||
total: String(Number(cur.total) - Number(prev.total)),
|
||||
};
|
||||
|
||||
// cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산
|
||||
@@ -287,10 +287,7 @@ export const buildGapRow = (
|
||||
const vCur = cur[k];
|
||||
const vPrev = prev[k];
|
||||
|
||||
const hasNumber = typeof vCur === "number" || typeof vPrev === "number";
|
||||
if (!hasNumber) return;
|
||||
|
||||
(gap as any)[k] = (typeof vCur === "number" ? vCur : 0) - (typeof vPrev === "number" ? vPrev : 0);
|
||||
(gap as any)[k] = String(Number(vCur) - Number(vPrev));
|
||||
});
|
||||
|
||||
return gap;
|
||||
|
||||
831
src/lib/lg-export-excel.ts
Normal file
831
src/lib/lg-export-excel.ts
Normal file
@@ -0,0 +1,831 @@
|
||||
// exportDashboardExcel.ts
|
||||
"use client";
|
||||
|
||||
import {formatRowLabel, isSampleRow} from "@/lib/lg-dashboard";
|
||||
import {DataColumn} from "@/components/lge-dashboard";
|
||||
|
||||
/**
|
||||
* 요구사항:
|
||||
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더(그룹 머지), (3) BANNER_GROUP 헤더(좌측 2칸 rowspan2 + 그룹 머지)
|
||||
* - Excel export (한 시트, 섹션 간 1행 띄움)
|
||||
* - 헤더 스타일:
|
||||
* group: background = --lg-gray-400
|
||||
* header: background = --lg-gray-600
|
||||
* font: #fff, bold
|
||||
*/
|
||||
|
||||
type HeaderStyleKey = "group" | "header";
|
||||
|
||||
type HeaderCell = {
|
||||
text: string;
|
||||
styleKey: HeaderStyleKey;
|
||||
rowSpan?: number; // default 1
|
||||
colSpan?: number; // default 1
|
||||
align?: "left" | "center" | "right";
|
||||
};
|
||||
|
||||
type HeaderBlock = {
|
||||
headerRows: HeaderCell[][];
|
||||
leafKeys: string[]; // 실제 데이터 컬럼 key 순서(좌->우)
|
||||
totalCols: number;
|
||||
};
|
||||
|
||||
export type Section<T extends Record<string, any>> = {
|
||||
title?: string;
|
||||
header: HeaderBlock;
|
||||
rows: T[];
|
||||
rowGap?: number; // default 1
|
||||
// 옵션
|
||||
colWidthByKey?: Record<string, number>;
|
||||
numFmtByKey?: Record<string, string>; // 예: "#,##0", "0.0", "0%"
|
||||
alignByKey?: Record<string, "left" | "center" | "right">;
|
||||
valueGetter?: (row: T, key: string) => any;
|
||||
};
|
||||
|
||||
type ExportOptions<T extends Record<string, any>> = {
|
||||
fileName?: string;
|
||||
sheetName?: string;
|
||||
sections: Section<T>[];
|
||||
// CSS 변수(없으면 기본값)
|
||||
groupBgVar?: string; // default "--lg-gray-400"
|
||||
headerBgVar?: string; // default "--lg-gray-600"
|
||||
borderVar?: string; // default "--lg-gray-300"
|
||||
};
|
||||
|
||||
/* =========================================================
|
||||
* 0) Object.entries 타입 보존
|
||||
* ========================================================= */
|
||||
const typedEntries = <T extends Record<string, any>>(obj: T) =>
|
||||
Object.entries(obj) as Array<[keyof T, T[keyof T]]>;
|
||||
|
||||
/* =========================================================
|
||||
* 1) CSS var -> Excel ARGB (HSL 토큰 "H S% L%" 지원)
|
||||
* ========================================================= */
|
||||
type RGB = { r: number; g: number; b: number };
|
||||
|
||||
function clamp255(n: number) {
|
||||
return Math.max(0, Math.min(255, Math.round(n)));
|
||||
}
|
||||
|
||||
function hslTokenToRgb(token: string): RGB | null {
|
||||
const m = token.trim().match(/^([\d.]+)\s+([\d.]+)%\s+([\d.]+)%$/);
|
||||
if (!m) return null;
|
||||
const h = parseFloat(m[1]) % 360;
|
||||
const s = parseFloat(m[2]) / 100;
|
||||
const l = parseFloat(m[3]) / 100;
|
||||
|
||||
const C = (1 - Math.abs(2 * l - 1)) * s;
|
||||
const hh = h / 60;
|
||||
const X = C * (1 - Math.abs((hh % 2) - 1));
|
||||
|
||||
let r1 = 0, g1 = 0, b1 = 0;
|
||||
if (0 <= hh && hh < 1) [r1, g1, b1] = [C, X, 0];
|
||||
else if (1 <= hh && hh < 2) [r1, g1, b1] = [X, C, 0];
|
||||
else if (2 <= hh && hh < 3) [r1, g1, b1] = [0, C, X];
|
||||
else if (3 <= hh && hh < 4) [r1, g1, b1] = [0, X, C];
|
||||
else if (4 <= hh && hh < 5) [r1, g1, b1] = [X, 0, C];
|
||||
else if (5 <= hh && hh < 6) [r1, g1, b1] = [C, 0, X];
|
||||
|
||||
const m2 = l - C / 2;
|
||||
return {
|
||||
r: clamp255((r1 + m2) * 255),
|
||||
g: clamp255((g1 + m2) * 255),
|
||||
b: clamp255((b1 + m2) * 255),
|
||||
};
|
||||
}
|
||||
|
||||
function hexToRgb(hex: string): RGB | null {
|
||||
const v = hex.trim();
|
||||
if (!v.startsWith("#")) return null;
|
||||
const h = v.slice(1);
|
||||
const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
|
||||
if (full.length !== 6) return null;
|
||||
return {
|
||||
r: parseInt(full.slice(0, 2), 16),
|
||||
g: parseInt(full.slice(2, 4), 16),
|
||||
b: parseInt(full.slice(4, 6), 16),
|
||||
};
|
||||
}
|
||||
|
||||
function rgbToArgb(rgb: RGB) {
|
||||
const toHex2 = (n: number) => n.toString(16).padStart(2, "0").toUpperCase();
|
||||
return `FF${toHex2(rgb.r)}${toHex2(rgb.g)}${toHex2(rgb.b)}`;
|
||||
}
|
||||
|
||||
function cssVarToExcelArgb(varName: string, fallbackHex = "#DDDDDD") {
|
||||
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
|
||||
const rgb = hslTokenToRgb(raw) ?? hexToRgb(raw) ?? hexToRgb(fallbackHex)!;
|
||||
return rgbToArgb(rgb);
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 2) 헤더 렌더러 (row/col merge + 스타일)
|
||||
* ========================================================= */
|
||||
type StylePack = {
|
||||
groupBg: string; // ARGB
|
||||
headerBg: string; // ARGB
|
||||
headerFont: string; // ARGB (white)
|
||||
border: string; // ARGB
|
||||
};
|
||||
|
||||
function writeMergedHeader(
|
||||
ws: any, // ExcelJS.Worksheet
|
||||
startRow: number,
|
||||
headerRows: HeaderCell[][],
|
||||
styles: StylePack
|
||||
) {
|
||||
const occupied = new Set<string>(); // "r,c" (0-based within header block)
|
||||
const isOcc = (r: number, c: number) => occupied.has(`${r},${c}`);
|
||||
const markOcc = (r: number, c: number) => occupied.add(`${r},${c}`);
|
||||
|
||||
const styleOf = (styleKey: HeaderStyleKey) => {
|
||||
const bg = styleKey === "group" ? styles.groupBg : styles.headerBg;
|
||||
return {
|
||||
fill: { type: "pattern", pattern: "solid", fgColor: { argb: bg } },
|
||||
font: { color: { argb: styles.headerFont }, bold: true },
|
||||
alignment: { vertical: "middle", wrapText: true },
|
||||
border: {
|
||||
top: { style: "thin", color: { argb: styles.border } },
|
||||
left: { style: "thin", color: { argb: styles.border } },
|
||||
bottom: { style: "thin", color: { argb: styles.border } },
|
||||
right: { style: "thin", color: { argb: styles.border } },
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const applyStyleRange = (r1: number, c1: number, r2: number, c2: number, st: any) => {
|
||||
for (let rr = r1; rr <= r2; rr++) {
|
||||
const row = ws.getRow(rr);
|
||||
for (let cc = c1; cc <= c2; cc++) {
|
||||
const cell = row.getCell(cc);
|
||||
cell.style = { ...(cell.style ?? {}), ...st };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
for (let hr = 0; hr < headerRows.length; hr++) {
|
||||
const rowCells = headerRows[hr];
|
||||
let colCursor = 0;
|
||||
|
||||
for (const hc of rowCells) {
|
||||
const rs = hc.rowSpan ?? 1;
|
||||
const cs = hc.colSpan ?? 1;
|
||||
|
||||
while (isOcc(hr, colCursor)) colCursor++;
|
||||
|
||||
const topRow = startRow + hr;
|
||||
const leftCol = colCursor + 1; // excel 1-based
|
||||
const bottomRow = topRow + rs - 1;
|
||||
const rightCol = leftCol + cs - 1;
|
||||
|
||||
const cell = ws.getRow(topRow).getCell(leftCol);
|
||||
cell.value = hc.text;
|
||||
|
||||
const st = styleOf(hc.styleKey);
|
||||
const horiz = hc.align ?? "center";
|
||||
cell.alignment = { ...(st.alignment ?? {}), horizontal: horiz };
|
||||
|
||||
if (rs > 1 || cs > 1) ws.mergeCells(topRow, leftCol, bottomRow, rightCol);
|
||||
|
||||
applyStyleRange(topRow, leftCol, bottomRow, rightCol, {
|
||||
...st,
|
||||
alignment: { ...(st.alignment ?? {}), horizontal: horiz },
|
||||
});
|
||||
|
||||
for (let r = hr; r < hr + rs; r++) {
|
||||
for (let c = colCursor; c < colCursor + cs; c++) {
|
||||
markOcc(r, c);
|
||||
}
|
||||
}
|
||||
|
||||
colCursor += cs;
|
||||
}
|
||||
|
||||
ws.getRow(startRow + hr).height = 20;
|
||||
}
|
||||
|
||||
return startRow + headerRows.length;
|
||||
}
|
||||
|
||||
type AutoFitOpt = {
|
||||
minColWidth?: number; // Excel column width units
|
||||
maxColWidth?: number;
|
||||
padding?: number; // width 여유(문자수 기준)
|
||||
baseRowHeight?: number; // pt
|
||||
maxRowHeight?: number; // pt
|
||||
useCanvasMeasure?: boolean; // 브라우저에서 measureText로 더 정확하게
|
||||
};
|
||||
|
||||
function autoFitApprox(ws: any, opt: AutoFitOpt = {}) {
|
||||
const o: Required<AutoFitOpt> = {
|
||||
minColWidth: opt.minColWidth ?? 8,
|
||||
maxColWidth: opt.maxColWidth ?? 60,
|
||||
padding: opt.padding ?? 2,
|
||||
baseRowHeight: opt.baseRowHeight ?? 15,
|
||||
maxRowHeight: opt.maxRowHeight ?? 120,
|
||||
useCanvasMeasure: opt.useCanvasMeasure ?? true,
|
||||
};
|
||||
|
||||
// 1) 머지 정보(내부 필드 사용: ExcelJS에서 공식 API가 없어서 근사 구현용)
|
||||
const mergeMap = buildMergeMap(ws);
|
||||
|
||||
// 2) 컬럼 폭 먼저 계산
|
||||
fitColumns(ws, mergeMap, o);
|
||||
|
||||
// 3) 그 다음 row height 계산 (wrapText/줄바꿈 고려)
|
||||
fitRows(ws, mergeMap, o);
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Column fit
|
||||
* --------------------------- */
|
||||
|
||||
function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
|
||||
const colCount = ws.columnCount ?? (ws.columns?.length ?? 0);
|
||||
const widths = new Array<number>(colCount + 1).fill(o.minColWidth);
|
||||
|
||||
ws.eachRow({ includeEmpty: false }, (row: any) => {
|
||||
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
|
||||
const text = getCellText(cell);
|
||||
if (!text) return;
|
||||
|
||||
// merged cell의 "master"만 처리 (중복 방지)
|
||||
const masterAddr = getMasterAddress(cell);
|
||||
const mi = mergeMap.get(masterAddr);
|
||||
if (mi && cell.address !== masterAddr) return;
|
||||
|
||||
const w = estimateWidth(text, cell, o); // width in "excel-char-like units"
|
||||
|
||||
if (mi && mi.colSpan > 1) {
|
||||
// 머지된 텍스트는 span만큼 나눠서 분배(머지 텍스트 때문에 한 컬럼이 과대해지는 현상 방지)
|
||||
const perCol = w / mi.colSpan;
|
||||
for (let c = mi.leftCol; c <= mi.rightCol; c++) {
|
||||
widths[c] = Math.max(widths[c], perCol);
|
||||
}
|
||||
} else {
|
||||
widths[colNumber] = Math.max(widths[colNumber], w);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
for (let c = 1; c <= colCount; c++) {
|
||||
const w = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
|
||||
ws.getColumn(c).width = w;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Row fit
|
||||
* --------------------------- */
|
||||
|
||||
function fitRows(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
|
||||
ws.eachRow({ includeEmpty: false }, (row: any) => {
|
||||
let maxLines = 1;
|
||||
|
||||
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
|
||||
const text = getCellText(cell);
|
||||
if (!text) return;
|
||||
|
||||
const masterAddr = getMasterAddress(cell);
|
||||
const mi = mergeMap.get(masterAddr);
|
||||
if (mi && cell.address !== masterAddr) return;
|
||||
|
||||
const wrap = !!cell.alignment?.wrapText;
|
||||
const explicitLines = text.split(/\r?\n/);
|
||||
|
||||
if (!wrap && explicitLines.length <= 1) return;
|
||||
|
||||
// 해당 셀의 사용 가능한 폭(머지면 합산)
|
||||
const availableWidth = mi
|
||||
? sumColumnWidth(ws, mi.leftCol, mi.rightCol, o)
|
||||
: getColumnWidth(ws, colNumber, o);
|
||||
|
||||
// 각 라인 별로 "줄바꿈이 몇 줄로 늘어나는지" 근사
|
||||
let cellLines = 0;
|
||||
for (const line of explicitLines) {
|
||||
const lineW = estimateWidth(line, cell, o);
|
||||
const needed = Math.max(1, Math.ceil(lineW / Math.max(1, availableWidth)));
|
||||
cellLines += needed;
|
||||
}
|
||||
|
||||
maxLines = Math.max(maxLines, cellLines);
|
||||
});
|
||||
|
||||
const h = clamp(o.baseRowHeight * maxLines, o.baseRowHeight, o.maxRowHeight);
|
||||
row.height = Math.max(row.height, h);
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Width estimation
|
||||
* --------------------------- */
|
||||
|
||||
function estimateWidth(text: string, cell: any, o: Required<AutoFitOpt>) {
|
||||
// 줄바꿈이면 가장 긴 라인 기준(컬럼 폭은 max line)
|
||||
const lines = text.split(/\r?\n/);
|
||||
const maxLine = lines.reduce((m, s) => (s.length > m.length ? s : m), "");
|
||||
|
||||
if (o.useCanvasMeasure && typeof document !== "undefined") {
|
||||
const px = measureTextPx(maxLine, cell);
|
||||
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도가 근사치로 많이 씀
|
||||
return px / 7;
|
||||
}
|
||||
|
||||
// canvas 못 쓰는 환경(또는 성능 이유) -> 문자폭 가중치 근사
|
||||
return estimateByCharWeight(maxLine);
|
||||
}
|
||||
|
||||
function measureTextPx(text: string, cell: any) {
|
||||
const canvas = getMeasureCanvas();
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
const fontName = cell.font?.name ?? "Calibri";
|
||||
const size = cell.font?.size ?? 11;
|
||||
const bold = cell.font?.bold ? "bold " : "";
|
||||
ctx.font = `${bold}${size}pt ${fontName}`;
|
||||
return ctx.measureText(text).width;
|
||||
}
|
||||
|
||||
let __canvas: HTMLCanvasElement | null = null;
|
||||
function getMeasureCanvas() {
|
||||
if (!__canvas) __canvas = document.createElement("canvas");
|
||||
return __canvas;
|
||||
}
|
||||
|
||||
// 한글/중국어/일본어 등 wide char 가중치 + 숫자/영문 가중치
|
||||
function estimateByCharWeight(s: string) {
|
||||
let w = 0;
|
||||
for (const ch of s) {
|
||||
if (isWideChar(ch)) w += 1.7; // 한글/한자/가나 등
|
||||
else if (ch === " ") w += 0.6;
|
||||
else if (/[A-Z]/.test(ch)) w += 1.1;
|
||||
else if (/[0-9]/.test(ch)) w += 1.0;
|
||||
else w += 0.9;
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
function isWideChar(ch: string) {
|
||||
const code = ch.codePointAt(0) ?? 0;
|
||||
// 대략적인 CJK 범위
|
||||
return (
|
||||
(code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo
|
||||
(code >= 0x2e80 && code <= 0x9fff) || // CJK, radicals
|
||||
(code >= 0xac00 && code <= 0xd7af) || // Hangul syllables
|
||||
(code >= 0x3040 && code <= 0x30ff) || // Hiragana/Katakana
|
||||
(code >= 0xff00 && code <= 0xffef) // Fullwidth forms
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Helpers: cell text
|
||||
* --------------------------- */
|
||||
|
||||
function getCellText(cell: any): string {
|
||||
const v = cell?.value;
|
||||
if (v === null || v === undefined) return "";
|
||||
|
||||
if (typeof v === "string") return v;
|
||||
if (typeof v === "number" || typeof v === "boolean") return String(v);
|
||||
if (v instanceof Date) return v.toISOString().slice(0, 10);
|
||||
|
||||
// ExcelJS value object types
|
||||
if (typeof v === "object") {
|
||||
if (v.richText) return v.richText.map((t: any) => t.text).join("");
|
||||
if (v.text) return String(v.text);
|
||||
if (v.formula) return v.result != null ? String(v.result) : "";
|
||||
if (v.hyperlink) return String(v.text ?? v.hyperlink);
|
||||
}
|
||||
|
||||
return String(v);
|
||||
}
|
||||
|
||||
function getMasterAddress(cell: any) {
|
||||
// merged cell이면 master가 존재
|
||||
if (cell?.isMerged && cell?.master?.address) return cell.master.address;
|
||||
return cell.address;
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Helpers: widths
|
||||
* --------------------------- */
|
||||
|
||||
function getColumnWidth(ws: any, col: number, o: Required<AutoFitOpt>) {
|
||||
const w = ws.getColumn(col)?.width;
|
||||
return typeof w === "number" ? w : o.minColWidth;
|
||||
}
|
||||
|
||||
function sumColumnWidth(ws: any, left: number, right: number, o: Required<AutoFitOpt>) {
|
||||
let sum = 0;
|
||||
for (let c = left; c <= right; c++) sum += getColumnWidth(ws, c, o);
|
||||
return sum;
|
||||
}
|
||||
|
||||
function clamp(v: number, min: number, max: number) {
|
||||
return Math.max(min, Math.min(max, v));
|
||||
}
|
||||
|
||||
/* ---------------------------
|
||||
* Merge map (internal _merges parsing)
|
||||
* --------------------------- */
|
||||
|
||||
type MergeInfo = {
|
||||
leftCol: number;
|
||||
rightCol: number;
|
||||
topRow: number;
|
||||
bottomRow: number;
|
||||
colSpan: number;
|
||||
};
|
||||
|
||||
function buildMergeMap(ws: any) {
|
||||
const map = new Map<string, MergeInfo>();
|
||||
|
||||
const merges = ws?._merges;
|
||||
if (!merges) return map;
|
||||
|
||||
// ws._merges: Map<string, any> 형태인 경우가 많음. key가 "A1:C1" 같은 range
|
||||
const keys: string[] =
|
||||
merges instanceof Map ? Array.from(merges.keys()) : Object.keys(merges);
|
||||
|
||||
for (const range of keys) {
|
||||
const parsed = parseRange(range);
|
||||
if (!parsed) continue;
|
||||
|
||||
const masterAddr = toA1(parsed.leftCol, parsed.topRow);
|
||||
map.set(masterAddr, {
|
||||
...parsed,
|
||||
colSpan: parsed.rightCol - parsed.leftCol + 1,
|
||||
});
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
// "A1:C3" -> 좌표
|
||||
function parseRange(range: string): Omit<MergeInfo, "colSpan"> | null {
|
||||
const parts = range.split(":");
|
||||
if (parts.length !== 2) return null;
|
||||
const a = parseA1(parts[0]);
|
||||
const b = parseA1(parts[1]);
|
||||
if (!a || !b) return null;
|
||||
|
||||
return {
|
||||
leftCol: Math.min(a.col, b.col),
|
||||
rightCol: Math.max(a.col, b.col),
|
||||
topRow: Math.min(a.row, b.row),
|
||||
bottomRow: Math.max(a.row, b.row),
|
||||
};
|
||||
}
|
||||
|
||||
function parseA1(a1: string): { col: number; row: number } | null {
|
||||
const m = a1.match(/^([A-Z]+)(\d+)$/i);
|
||||
if (!m) return null;
|
||||
const col = lettersToCol(m[1].toUpperCase());
|
||||
const row = parseInt(m[2], 10);
|
||||
return { col, row };
|
||||
}
|
||||
|
||||
function lettersToCol(letters: string) {
|
||||
let n = 0;
|
||||
for (const ch of letters) {
|
||||
n = n * 26 + (ch.charCodeAt(0) - 64);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
function toA1(col: number, row: number) {
|
||||
return `${colToLetters(col)}${row}`;
|
||||
}
|
||||
|
||||
function colToLetters(col: number) {
|
||||
let n = col;
|
||||
let s = "";
|
||||
while (n > 0) {
|
||||
const r = (n - 1) % 26;
|
||||
s = String.fromCharCode(65 + r) + s;
|
||||
n = Math.floor((n - 1) / 26);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 3) 헤더 빌더 3종
|
||||
* ========================================================= */
|
||||
|
||||
/**
|
||||
* (1) PRODUCT_KEY_MAP:
|
||||
* - 첫 칸 비움
|
||||
* - 나머지는 일반 헤더
|
||||
*/
|
||||
export function buildHeader_ProductKeyMap(
|
||||
productKeyMap: Record<string, string>,
|
||||
rowHeadKey = "rowLabel"
|
||||
): HeaderBlock {
|
||||
const entries = typedEntries(productKeyMap);
|
||||
|
||||
const headerRow: HeaderCell[] = [
|
||||
{ text: "", styleKey: "header", align: "center" },
|
||||
...entries.map(([, label]) => ({
|
||||
text: String(label),
|
||||
styleKey: "header" as const,
|
||||
align: "center" as const,
|
||||
})),
|
||||
];
|
||||
|
||||
const leafKeys = [rowHeadKey, ...entries.map(([k]) => String(k))];
|
||||
return { headerRows: [headerRow], leafKeys, totalCols: headerRow.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* (2) LIFE_STAGE_COLUMNS:
|
||||
* - 1행: group 머지(같은 group 연속 구간)
|
||||
* - 2행: header 텍스트
|
||||
*
|
||||
* group 없는 컬럼은 1행에 빈 셀(그룹 스타일) 1칸 채움
|
||||
*/
|
||||
export type GaugeColumn = {
|
||||
key: string;
|
||||
header: string;
|
||||
rowHead?: boolean;
|
||||
group?: string;
|
||||
align?: "left" | "center" | "right";
|
||||
};
|
||||
|
||||
export function buildHeader_LifeStageColumns(cols: GaugeColumn[]): HeaderBlock {
|
||||
const row1: HeaderCell[] = [];
|
||||
const row2: HeaderCell[] = [];
|
||||
const leafKeys = cols.map((c) => c.key);
|
||||
|
||||
let i = 0;
|
||||
while (i < cols.length) {
|
||||
const c = cols[i];
|
||||
const g = c.group;
|
||||
|
||||
if (!g) {
|
||||
row1.push({ text: "", styleKey: "group", colSpan: 1, align: "center" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let j = i + 1;
|
||||
while (j < cols.length && cols[j].group === g) j += 1;
|
||||
const span = j - i;
|
||||
|
||||
row1.push({ text: g, styleKey: "group", colSpan: span, align: "center" });
|
||||
i = j;
|
||||
}
|
||||
|
||||
for (const c of cols) {
|
||||
row2.push({ text: c.header ?? "", styleKey: "header", colSpan: 1, align: "center" });
|
||||
}
|
||||
|
||||
return { headerRows: [row1, row2], leafKeys, totalCols: cols.length };
|
||||
}
|
||||
|
||||
export function buildHeader_DataColumn<T>(cols: DataColumn<T>[]): HeaderBlock {
|
||||
const row1: HeaderCell[] = [];
|
||||
const row2: HeaderCell[] = [];
|
||||
|
||||
const leafKeys = cols.map((c) => String(c.key));
|
||||
|
||||
// 1행: 그룹 머지 / rowspan 처리
|
||||
let i = 0;
|
||||
while (i < cols.length) {
|
||||
const c = cols[i];
|
||||
const rs = c.headRowSpan ?? 1;
|
||||
|
||||
// (A) rowspan=2면: 1행에 header를 올리고(세로머지), 2행은 빈 칸(placeholder)
|
||||
if (rs === 2) {
|
||||
row1.push({
|
||||
text: c.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
rowSpan: 2,
|
||||
align: c.align ?? "center",
|
||||
});
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// (B) 그룹 구간 처리
|
||||
const gKey = c.groupKey ?? c.group;
|
||||
if (gKey) {
|
||||
let j = i + 1;
|
||||
while (j < cols.length) {
|
||||
const cj = cols[j];
|
||||
const rsj = cj.headRowSpan ?? 1;
|
||||
const gKeyJ = cj.groupKey ?? cj.group;
|
||||
|
||||
// rowspan=2가 섞이면 그룹 머지 끊음(안정성)
|
||||
if (rsj === 2) break;
|
||||
if (gKeyJ !== gKey) break;
|
||||
|
||||
j += 1;
|
||||
}
|
||||
|
||||
const span = j - i;
|
||||
|
||||
row1.push({
|
||||
text: c.group ?? "",
|
||||
styleKey: "group",
|
||||
colSpan: span,
|
||||
align: "center",
|
||||
});
|
||||
|
||||
// 2행: 그룹 구간의 각 컬럼 header
|
||||
for (let k = i; k < j; k++) {
|
||||
const ck = cols[k];
|
||||
row2.push({
|
||||
text: ck.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
align: ck.align ?? "center",
|
||||
});
|
||||
}
|
||||
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
|
||||
// (C) 그룹도 없고 rowspan도 아니면: 1행에 빈 group 셀 1개, 2행에 header
|
||||
row1.push({
|
||||
text: "",
|
||||
styleKey: "group",
|
||||
colSpan: 1,
|
||||
align: "center",
|
||||
});
|
||||
row2.push({
|
||||
text: c.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
align: c.align ?? "center",
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
headerRows: [row1, row2],
|
||||
leafKeys,
|
||||
totalCols: cols.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* (3) BANNER_GROUP + BANNER_KEY_MAP:
|
||||
* - A1: "" (rowspan2)
|
||||
* - B1: "전체" (rowspan2) key=total
|
||||
* - C1~: group(label) (colSpan = keys.length)
|
||||
* - 2행: 각 key의 라벨(BANNER_KEY_MAP[key])
|
||||
*/
|
||||
export function buildHeader_Banner<K extends string>(
|
||||
bannerGroup: Record<string, { label: string; keys: readonly K[] }>,
|
||||
bannerKeyMap: Record<K, string>,
|
||||
rowHeadKey = "rowLabel",
|
||||
totalKey = "total"
|
||||
): HeaderBlock {
|
||||
const groups = Object.values(bannerGroup);
|
||||
|
||||
const row1: HeaderCell[] = [
|
||||
{ text: "", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
|
||||
{ text: "전체", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
|
||||
];
|
||||
|
||||
const row2: HeaderCell[] = [];
|
||||
const leafKeys: string[] = [rowHeadKey, totalKey];
|
||||
|
||||
for (const g of groups) {
|
||||
row1.push({ text: g.label, styleKey: "group", colSpan: g.keys.length, align: "center" });
|
||||
|
||||
for (const k of g.keys) {
|
||||
row2.push({ text: bannerKeyMap[k] ?? k, styleKey: "header", colSpan: 1, align: "center" });
|
||||
leafKeys.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
const totalCols = 2 + groups.reduce((acc, g) => acc + g.keys.length, 0);
|
||||
return { headerRows: [row1, row2], leafKeys, totalCols };
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 4) Export (one sheet, 섹션 간 1행 띄움)
|
||||
* ========================================================= */
|
||||
export async function exportDashboardExcel<T extends Record<string, any>>(opts: ExportOptions<T>) {
|
||||
const {
|
||||
fileName = "export.xlsx",
|
||||
sheetName = "Export",
|
||||
sections,
|
||||
groupBgVar = "--lg-gray-400",
|
||||
headerBgVar = "--lg-gray-600",
|
||||
borderVar = "--lg-gray-300",
|
||||
} = opts;
|
||||
|
||||
// ExcelJS import (환경에 따라 min 빌드가 더 잘 먹는 경우가 있음)
|
||||
const ExcelJS = await import("exceljs");
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet(sheetName);
|
||||
|
||||
const stylePack: StylePack = {
|
||||
groupBg: cssVarToExcelArgb(groupBgVar, "#9CA3AF"),
|
||||
headerBg: cssVarToExcelArgb(headerBgVar, "#4B5563"),
|
||||
headerFont: "FFFFFFFF", // #fff
|
||||
border: cssVarToExcelArgb(borderVar, "#D1D5DB"),
|
||||
};
|
||||
|
||||
let rowCursor = 1;
|
||||
|
||||
for (const sec of sections) {
|
||||
const gap = sec.rowGap ?? 1;
|
||||
const { header, rows } = sec;
|
||||
|
||||
// (선택) 섹션 타이틀
|
||||
if (sec.title) {
|
||||
const r = ws.getRow(rowCursor);
|
||||
const c = r.getCell(1);
|
||||
c.value = sec.title;
|
||||
c.font = { bold: true, size: 13 };
|
||||
r.height = 22;
|
||||
if (header.totalCols > 1) ws.mergeCells(rowCursor, 1, rowCursor, header.totalCols);
|
||||
rowCursor += 1;
|
||||
}
|
||||
|
||||
// 헤더
|
||||
rowCursor = writeMergedHeader(ws, rowCursor, header.headerRows, stylePack);
|
||||
|
||||
// 컬럼 width
|
||||
if (sec.colWidthByKey) {
|
||||
header.leafKeys.forEach((k, idx) => {
|
||||
const w = sec.colWidthByKey?.[k];
|
||||
if (w) ws.getColumn(idx + 1).width = w;
|
||||
});
|
||||
} else {
|
||||
// 기본: 첫 컬럼 넓게, 나머지 적당히
|
||||
header.leafKeys.forEach((k, idx) => {
|
||||
ws.getColumn(idx + 1).width = idx === 0 ? 22 : 14;
|
||||
});
|
||||
}
|
||||
|
||||
const valueGetter = sec.valueGetter ?? ((r: T, k: string) => (r as any)[k]);
|
||||
|
||||
// 데이터
|
||||
for (const row of rows) {
|
||||
const excelRow = ws.getRow(rowCursor);
|
||||
const sampleRow = isSampleRow(valueGetter(row, header.leafKeys.at(0) ?? ""));
|
||||
|
||||
header.leafKeys.forEach((key, idx) => {
|
||||
const cell = excelRow.getCell(idx + 1);
|
||||
const v = valueGetter(row, key);
|
||||
const isColHeader = idx === 0;
|
||||
|
||||
if (v === null || v === undefined || v === "") cell.value = null;
|
||||
else if (typeof v === "number") cell.value = v;
|
||||
else if (isColHeader) cell.value = formatRowLabel(String(v));
|
||||
else if (sampleRow) cell.value = `(${String(v)})`;
|
||||
else cell.value = String(v);
|
||||
|
||||
const align =
|
||||
sec.alignByKey?.[key] ??
|
||||
(typeof v === "number" ? "right" : "left");
|
||||
|
||||
cell.alignment = { vertical: "middle", horizontal: align, wrapText: true };
|
||||
|
||||
const numFmt = sec.numFmtByKey?.[key];
|
||||
if (numFmt) cell.numFmt = numFmt;
|
||||
|
||||
cell.border = {
|
||||
top: { style: "thin", color: { argb: stylePack.border } },
|
||||
left: { style: "thin", color: { argb: stylePack.border } },
|
||||
bottom: { style: "thin", color: { argb: stylePack.border } },
|
||||
right: { style: "thin", color: { argb: stylePack.border } },
|
||||
};
|
||||
|
||||
if(isColHeader){
|
||||
cell.font = { bold: true };
|
||||
}
|
||||
});
|
||||
|
||||
excelRow.height = 18;
|
||||
rowCursor += 1;
|
||||
}
|
||||
|
||||
rowCursor += gap;
|
||||
}
|
||||
|
||||
autoFitApprox(ws, {
|
||||
minColWidth: 8,
|
||||
maxColWidth: 55,
|
||||
baseRowHeight: 15,
|
||||
maxRowHeight: 120,
|
||||
useCanvasMeasure: true,
|
||||
});
|
||||
// 다운로드
|
||||
const buf = await wb.xlsx.writeBuffer();
|
||||
const blob = new Blob([buf], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = fileName;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
Reference in New Issue
Block a user