이번 글에서는 react에서 excel을 생성하는 방법을 쓸 예정입니다.

 

우선 사용할 라이브러리는 xlsx와 fileSaver 2개를 같이 사용할 예정이다.

 

yarn add xlsx file-saver

 

터미널에 입력하여 xlsx와 file-saver를 먼저 받아주고,

 

import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

const excelFileType =
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const excelFileExtension = '.xlsx';
const excelFileName = `파일명`;

 

파일명과 파일 타입 등을 설정하고, 

 

// 예시용 데이터
const data = [
  {
    id: '1',
    name: 'Jay',
    age: '29',
  },
  {
    id: '2',
    name: 'hong',
    age: '25',
  },
  {
    id: '3',
    name: 'Yua',
    age: '23',
  },
];

//함수 실행 시 예시를 사용하여 excel 생성
const excelDownload = (
    excelData: Array<{
      id: string;
      name: string;
      age: string;
    }>
  ) => {
    const ws = XLSX.utils.aoa_to_sheet([[`Databank`], ['ID', '이름', '나이']]);
    excelData.map((data: { id: string; name: string; age: string }) => {
      const sheetData: Array<string> = [data.id, data.name, data.age];

      XLSX.utils.sheet_add_aoa(ws, [sheetData], {
        origin: -1,
      });

      return false;
    });
    const wb: any = { Sheets: { data: ws }, SheetNames: ['data'] };
    const excelButter = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const excelFile = new Blob([excelButter], { type: excelFileType });
    FileSaver.saveAs(excelFile, excelFileName + excelFileExtension);
  };

 

엑셀을 만들 수 있는 함수를 생성한다.

 

const ws = XLSX.utils.aoa_to_sheet([[`Databank`], ['ID', '이름', '나이']]);

 

이 코드는 엑셀 생성시 위쪽에 생성되는 헤더쪽이다. 제목이나 데이터의 컬럼명 등을 입력할수 있고, 빈칸으로 놔두어 행을 비울수도 있다.

배열 형태로 입력해야되며 배열에 인덱스마다 값이 입력된다.

 

excelData.map((data: { id: string; name: string; age: string }) => {
      const sheetData: Array<string> = [data.id, data.name, data.age];

      XLSX.utils.sheet_add_aoa(ws, [sheetData], {
        origin: -1,
      });
      
      ws['!cols'] = [{wpx:50},{wpx:50},{wpx:50}]

      return false;
    });

 

이 코드는 받아온 데이터에서 한 행에 들어가는 내용을 나타낸다. 데이터에서 원하는 데이터만 출력하거나, 특정 형태로 수정하여 출력할 수 있다.

ws['!cols'] 코드를 통하여 열 넓이를 조절할 수 있다 배열 형태로 wpx를 넣으면 숫자값만큼의 크기를 가진다.

 

const wb: any = { Sheets: { data: ws }, SheetNames: ['data'] };
    const excelButter = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const excelFile = new Blob([excelButter], { type: excelFileType });
    FileSaver.saveAs(excelFile, excelFileName + excelFileExtension);

 

마지막 코드는 위의 데이터와 파일 설정 이름 등을 합치고, FileSaver를 통하여 저장할 수 있다.