sn: 지반침하 지도상세정보 엑셀다운로드
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
/** 서로 다른 구조의 시트를 하나의 브라우저 다운로드 파일로 생성한다. */
|
||||
import type { WorkBook } from "xlsx";
|
||||
|
||||
export type ExcelCellValue = string | number | boolean | null;
|
||||
export type ExcelSheetSpec = {
|
||||
name: string;
|
||||
rows: ExcelCellValue[][];
|
||||
columnWidths?: number[];
|
||||
autoFilterRange?: string;
|
||||
mergeRanges?: string[];
|
||||
};
|
||||
export type ExcelWorkbookOptions = {
|
||||
fileName: string;
|
||||
sheets: ExcelSheetSpec[];
|
||||
};
|
||||
|
||||
/** 금지 문자·길이·대소문자 중복을 처리해 유효한 시트명을 만든다. */
|
||||
const uniqueSheetName = (name: string, used: Set<string>) => {
|
||||
const base =
|
||||
name
|
||||
.replace(/[\\/?*[\]:\u0000-\u001f]/g, "_")
|
||||
.replace(/^'+|'+$/g, "")
|
||||
.trim()
|
||||
.slice(0, 31) || "Sheet";
|
||||
let result = base;
|
||||
let index = 2;
|
||||
while (used.has(result.toLowerCase())) {
|
||||
const suffix = `_${index++}`;
|
||||
result = `${base.slice(0, 31 - suffix.length)}${suffix}`;
|
||||
}
|
||||
used.add(result.toLowerCase());
|
||||
return result;
|
||||
};
|
||||
|
||||
/** 명시적인 셀 배열을 사용해 문자열을 수식으로 해석하지 않고 시트를 구성한다. */
|
||||
export const buildExcelWorkbook = async (
|
||||
sheets: ExcelSheetSpec[],
|
||||
): Promise<WorkBook> => {
|
||||
if (sheets.length === 0) throw new Error("다운로드할 시트가 없습니다.");
|
||||
const XLSX = await import("xlsx");
|
||||
const workbook = XLSX.utils.book_new();
|
||||
const usedNames = new Set<string>();
|
||||
for (const sheet of sheets) {
|
||||
const worksheet = XLSX.utils.aoa_to_sheet(sheet.rows);
|
||||
worksheet["!cols"] = sheet.columnWidths?.map((wch) => ({ wch }));
|
||||
if (sheet.autoFilterRange)
|
||||
worksheet["!autofilter"] = { ref: sheet.autoFilterRange };
|
||||
if (sheet.mergeRanges)
|
||||
worksheet["!merges"] = sheet.mergeRanges.map(XLSX.utils.decode_range);
|
||||
// 긴 주소·원인과 명시적인 개행이 들어간 셀을 읽기 좋게 표시한다.
|
||||
sheet.rows.forEach((row, r) =>
|
||||
row.forEach((value, c) => {
|
||||
const cell = worksheet[XLSX.utils.encode_cell({ r, c })];
|
||||
if (cell && typeof value === "string")
|
||||
cell.s = { alignment: { wrapText: true, vertical: "top" } };
|
||||
}),
|
||||
);
|
||||
XLSX.utils.book_append_sheet(
|
||||
workbook,
|
||||
worksheet,
|
||||
uniqueSheetName(sheet.name, usedNames),
|
||||
);
|
||||
}
|
||||
return workbook;
|
||||
};
|
||||
|
||||
/** 업무별 조회와 값 변환이 끝난 시트들을 순서대로 XLSX 파일에 저장한다. */
|
||||
export const downloadExcelWorkbook = async ({
|
||||
fileName,
|
||||
sheets,
|
||||
}: ExcelWorkbookOptions) => {
|
||||
if (typeof window === "undefined")
|
||||
throw new Error("엑셀 다운로드는 브라우저에서만 사용할 수 있습니다.");
|
||||
const workbook = await buildExcelWorkbook(sheets);
|
||||
const normalized =
|
||||
fileName
|
||||
.replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_")
|
||||
.replace(/[. ]+$/g, "")
|
||||
.trim() || "download";
|
||||
const XLSX = await import("xlsx");
|
||||
XLSX.writeFile(
|
||||
workbook,
|
||||
/\.xlsx$/i.test(normalized) ? normalized : `${normalized}.xlsx`,
|
||||
{
|
||||
bookType: "xlsx",
|
||||
compression: true,
|
||||
cellStyles: true,
|
||||
},
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user