카테고리 없음
[NestJS] JSON to Excel
포시
2024. 2. 23. 14:43
728x90
npm install xlsx fs
import * as fs from 'fs';
import * as XLSX from 'xlsx';
// ... 생략
jsonToExcel(res) {
const originalJSON = {
"AD": {
"name": "Andorra",
"phone": "376",
"flag": "🇦🇩"
},
"AE": {
"name": "United Arab Emirates",
"phone": "97",
"flag": "🇦🇪"
},
// ...
};
const transformedArray = Object.entries(originalJSON).map(([iso2, country]) => ({
name: country.name,
phone: country.phone,
iso2: iso2
}));
// step 1. workbook 생성
const wb = XLSX.utils.book_new();
// step 2. 시트 만들기
const newWorksheet = XLSX.utils.json_to_sheet(transformedArray);
// step 3. workbook에 새로만든 워크시트에 이름을 주고 붙임.
XLSX.utils.book_append_sheet(wb, newWorksheet, 'Sheet1');
const wbOptions = { bookType: 'xlsx', type: 'binary' };
const filename = 'test.xlsx';
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
// step 4. 파일을 로컬에 생성합니다.
XLSX.writeFile(wb, filename, wbOptions); // write workbook file
// step 5. 생성된 파일을 client 에 전송합니다.
const stream = fs.createReadStream(filename); // create read stream
stream.pipe(res);
}
참고
https://velog.io/@peter0618/NestJS-excel-업로드다운로드
NestJS excel 업로드/다운로드
엑셀을 다루는 xlsx 패키지와, 파일을 다루는 fs 패키지를 설치합니다.엑셀 업로드 테스트를 위한 엑셀파일을 준비합니다.위와 같은 엑셀파일을 업로드하면, 서버에서 엑셀파일을 파싱해서 json형
velog.io
728x90