Front-End/React

엑셀 다운로드

Voyage_dev 2023. 7. 2. 13:15

이번에 회사에서 관리자 페이지를 구현하다가 요구사항이 들어왔다. 바로 목록 즉, 다양한 데이터들이 들어있는 테이블을 엑셀 파일로 다운로드 할 수 있게 구현해 달라였다. 엑셀 다운로드는 처음 구현하다 보니 방법이랑 코드를 정리해 볼려고 한다.

 

React를 이용한 엑셀 다운로드 구현하기

 

라이브러리 설치

yarn add xlsx

or

npm i xlsx

import

import * as XLSX from "xlsx";

다운로드 할 데이터 생성

// promotionAppliedData로 다운로드 하고 싶은 부분만 다시 세팅

const filterDataToDownload = useMemo(() => {
    return promotionAppliedData?.map((res: PromotionAttriProps) => {
      const { attributes } = res;
      return {
        프로모션: attributes.promotionTitle,
        참여유저: attributes.userName,
        전화번호: attributes.userPhoneNumber,
        퍼피서더명: attributes.puppyssadorName,
        기부비율: attributes.donationPercentage,
        참여금액: attributes.totalOrderAmount,
        수익금액: attributes.proceedsAmount,
        기부금액: attributes.donateAmount,
        네이버아이디: attributes.naverId,
        혜택1: attributes.benefitNaverCoupon,
        혜택2: attributes.benefitProduct,
        기부등록일: attributes.donateDate,
        네이버쿠폰발송여부: attributes.isNaverCouponSent,
        배송여부: attributes.isSent,
        우편번호: attributes.zipcode,
        주소: attributes.address,
      };
    });
  }, [promotionAppliedData]);

필요한 곳에 버튼 생성 및 onClick 연결

<Button
 label="다운로드"
 backgroundColor="#f56969"
 color="#f2f2f2"
 width="100px"
 height="100px"
 isValid
 onClick={() =>
  totalPromotionDataDownloadXlsx(filterDataToDownload)
	  }
 />

다운로드 함수 utils

import { PromotionAttriProps } from "store/Admin/types";
import * as XLSX from "xlsx";

export const totalPromotionDataDownloadXlsx = (data: PromotionAttriProps[]) => {
  const excelHandler = {
    getExcelFileName: () => {
      return "유저 데이터.xlsx";
    },
    getSheetName: () => {
      return "userData";
    },
    getExcelData: () => {
      return data;
    },
    getWorksheet: () => {
      return XLSX.utils.json_to_sheet(excelHandler.getExcelData());
    },
  };

  const datas = excelHandler.getWorksheet();
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, datas, excelHandler.getSheetName());
  XLSX.writeFile(workbook, excelHandler.getExcelFileName());
};
// json 데이터를 excel로 내려받는 설정 (변환)
 getWorksheet: () => {
   return XLSX.utils.json_to_sheet(excelHandler.getExcelData());
  },

다양한 메소드

xlsx.utils.sheet_to_csv generates CSV
xlsx.utils.sheet_to_txt generates UTF16 Formatted Text
xlsx.utils.sheet_to_html generates HTML
xlsx.utils.sheet_to_json generates an array of objects
xlsx.utils.sheet_to_formulae generates a list of formulae
// Excel workbook
const workbook = XLSX.utils.book_new();

// 새로운 워크북 즉, 시트들을 포함하는 워크북 객체를 생성
// 생성한 새로운 워크북에 워크시트를 묶어주는, workbook에 다운로드 받으려는 데이터와 해당 파일 이름 설정
XLSX.utils.book_append_sheet(workbook, datas, excelHandler.getSheetName());
// File 내보내기 (다운받을 때, 뜨는 파일명 설정)
XLSX.writeFile(workbook, excelHandler.getExcelFileName());