티스토리 뷰

1. exceljs 라이브러리를 설치합니다.

 npm i exceljs

2. 다운로드를 위해 file-saver를 설치합니다. 

npm i file-saver

3.excel을 만들어줍니다.

*버튼을 클릭 했을 때 엑셀이 추출 되게 구현할 예정이므로 버튼이 클릭했을 때 실행되는 함수 안에 엑셀을 만들어주는 코드를 구현합니다.  

 

1) workbook을 만들어줍니다.  

 const workbook = new ExcelJS.Workbook();

2) 엑셀 시트를 만들어줍니다.

- 아래의 코드는 같은 코드이지만 2-1의 코드는 엑셀 sheet에 color를 추가해줬습니다. 

  //2. 엑셀 시트 생성
    //const worksheet = workbook.addWorksheet("내역 리스트"); // sheet 이름이 My Sheet

    //2-1. 엑셀 시트 생성
    const worksheet = workbook.addWorksheet("내역 리스트", {
      properties: { tabColor: { argb: "FFC0000" } },
    });

3. 엑셀 테이블의 header를 만들어줍니다.

const header = ["Id", "회원번호", "분류", "포인트", "유형", "내용", "날짜"];

를 먼저 선언해준 후, header를 그려줍니다( + 컴포넌트 스타일로 스타일도 추가해줍니다.) 

 const tableHeader = worksheet.addRow(header);

    tableHeader.height = 30.75;
    tableHeader.eachCell((cell, colNum) => {
      styleHeaderCell(cell);
      worksheet.getColumn(colNum).width = hederWidth[colNum - 1];
    });
const styleHeaderCell = (cell) => {
  cell.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "ffebebeb" },
  };
  cell.border = {
    bottom: { style: "thin", color: { argb: "-100000f" } },
    right: { style: "thin", color: { argb: "-100000f" } },
  };
  cell.font = {
    name: "Arial",
    size: 12,
    bold: true,
    color: { argb: "ff252525" },
  };
  cell.alignment = {
    vertical: "middle",
    horizontal: "center",
    wrapText: true,
  };
};

4. 데이터를 엑셀에 추가해줍니다. ( + 컴포넌트 스타일로 스타일도 추가해줍니다.) 

 rows.forEach(({ id, owner, action, news, type, desc, createdAt }) => {
      const rowDatas = [
        id,
        owner,
        action === "put" ? "적립" : "정산",
        Number(news),
        chkType(type),
        desc ?? "",
        moment(createdAt * 1000).format("YYYY-MM-DD HH:mm:ss"),
      ];

      const dataRow = worksheet.addRow(rowDatas);
      dataRow.eachCell((cell, colNum) => {
        styleData(cell);
      });
    });
const styleData = (cell) => {
  cell.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "ffffffff" },
  };
  cell.border = {
    bottom: { style: "thin", color: { argb: "-100000f" } },
    right: { style: "thin", color: { argb: "-100000f" } },
  };
  cell.font = {
    name: "Arial",
    size: 10,
    bold: false,
    color: { argb: "ff252525" },
  };
  cell.alignment = {
    vertical: "middle",
    horizontal: "center",
    wrapText: true,
  };
};

5. 다운로드 기능을 추가합니다.

   // 다운로드
    const mimeType = {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    };
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], mimeType);
    saveAs(blob, "testExcel.xlsx");
  };

참고용 전체 코드

import React from "react";
import * as ExcelJS from "exceljs";
import { saveAs } from "file-saver";
import moment from "moment";

// 
const list = [{ 
	id: "1",
    owner:'123145124'
    action: "abc",
    kind: "123",
    news: 1,
    type:"체크"
    createdAt: 123456789(unix로 전달받음), 
    type: "attention",
    desc: null, 
   }];
    
const header = ["Id", "회원번호", "분류", "포인트", "유형", "내용", "날짜"];
const hederWidth = [10, 30, 20, 20, 20, 50, 20];

export default function Excel() {
  const downExcel = async (rows) => {
    
    const workbook = new ExcelJS.Workbook();
  
    //const worksheet = workbook.addWorksheet("내역 리스트"); // sheet 이름이 My Sheet

    const worksheet = workbook.addWorksheet(" 내역 리스트", {
      properties: { tabColor: { argb: "FFC0000" } },
    });

 
    const tableHeader = worksheet.addRow(header);

    tableHeader.height = 30.75;
    tableHeader.eachCell((cell, colNum) => {
      styleHeaderCell(cell);
      worksheet.getColumn(colNum).width = hederWidth[colNum - 1];
    });
    
    rows.forEach(({ id, owner, action, news, type, desc, createdAt }) => {
      const rowDatas = [
        id,
        owner,
        action === "put" ? "적립" : "정산",
        Number(news),
        type,
        desc ?? "",
        moment(createdAt * 1000).format("YYYY-MM-DD HH:mm:ss"),
        //unix로 전달받음 시간을 "YYYY-MM-DD HH:mm:ss"형태로 변환 
      ];

      const dataRow = worksheet.addRow(rowDatas);
      dataRow.eachCell((cell, colNum) => {
        styleData(cell);
      });
    });

    // 다운로드
    const mimeType = {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    };
    const buffer = await workbook.xlsx.writeBuffer();
    const blob = new Blob([buffer], mimeType);
    saveAs(blob, "testExcel.xlsx");
  };
  return (
    <div>
      <button onClick={() => downExcel(list)}>엑셀 내보내기!!</button>
    </div>
  );
}
const styleHeaderCell = (cell) => {
  cell.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "ffebebeb" },
  };
  cell.border = {
    bottom: { style: "thin", color: { argb: "-100000f" } },
    right: { style: "thin", color: { argb: "-100000f" } },
  };
  cell.font = {
    name: "Arial",
    size: 12,
    bold: true,
    color: { argb: "ff252525" },
  };
  cell.alignment = {
    vertical: "middle",
    horizontal: "center",
    wrapText: true,
  };
};

const styleData = (cell) => {
  cell.fill = {
    type: "pattern",
    pattern: "solid",
    fgColor: { argb: "ffffffff" },
  };
  cell.border = {
    bottom: { style: "thin", color: { argb: "-100000f" } },
    right: { style: "thin", color: { argb: "-100000f" } },
  };
  cell.font = {
    name: "Arial",
    size: 10,
    bold: false,
    color: { argb: "ff252525" },
  };
  cell.alignment = {
    vertical: "middle",
    horizontal: "center",
    wrapText: true,
  };
};

'프론트엔드 > React' 카테고리의 다른 글

[React] React Portal  (0) 2023.08.11
[React] Tab Menu 탭 메뉴 기능 구현  (0) 2023.06.27
[React] Hooks  (0) 2023.05.22
[react-router-dom] useParams  (0) 2023.02.17
Redux  (0) 2023.02.03
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함