이전 회사에서 거래명세서와 같이 특정 형식을 엑셀로 다운받는 기능을 구현하는 경우가 있었다.
구글링을 통해 exceljs 라이브러리를 사용하는것이 그나마 간단히 구현 가능하다고 판단되어
아래와 같이 구현했다.
import * as Excel from "exceljs";
export default function onQuoteExcelDownload(
data1: string,
data2: string,
) {
const workbook = new Excel.Workbook();
const sheet1 = workbook.addWorksheet("거래명세서", {
views: [{ showGridLines: false }],
});
//데이터 열
sheet1.columns = [
{ header: "data1", key: "data1" },
{ header: "data2", key: "data2" },
];
//1행
sheet1.mergeCells("A1:C2");
sheet1.getCell("C2").value = "거래명세서";
sheet1.getCell("C2").font = { size: 22 };
sheet1.getCell("C2").alignment = { vertical: "top", horizontal: "left" };
//컬럼 크기 지정
if (sheet1.columns && sheet1.columns.length > 0) {
sheet1.columns.forEach((item) => {
item.width = 7;
});
}
//칼럼 높이 지정
sheet1.eachRow((item) => {
item.height = 18;
});
//파일 다운로드
workbook.xlsx
.writeBuffer()
.then((data: any) => {
const blob = new Blob([data], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = window.URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = "거래명세서.xlsx";
anchor.click();
window.URL.revokeObjectURL(url);
})
.catch((error) => {
console.log(error);
});
}
라이브러리 공식 페이지를 참고하여 위와 같이 구성해주면된다.
그러나 해당 방식으론 원하는 UI를 구현하기 위해선 엄청난 시간과 노력이 들어가므로
다른 방식을 찾는것이 좋을거 같다