리액트 엑셀 다운로드

2023. 4. 28. 15:42Library/React

728x90
반응형

Sheet JS와 File-saver 사용

 

ReactJS | SheetJS Community Edition

 

ReactJS | SheetJS Community Edition

ReactJS is a JS library for building user interfaces.

docs.sheetjs.com

npm i --save https://cdn.sheetjs.com/xlsx-0.19.3/xlsx-0.19.3.tgz

 

 

 

file-saver - npm (npmjs.com)

 

file-saver

An HTML5 saveAs() FileSaver implementation. Latest version: 2.0.5, last published: 2 years ago. Start using file-saver in your project by running `npm i file-saver`. There are 3933 other projects in the npm registry using file-saver.

www.npmjs.com

npm install file-saver --save

 


1. 기본

import React from 'react'
import * as XLSX from 'xlsx'
import * as FileSaver from "file-saver"

const Excel = () => {

	const excelDownload = () => {
        const excelFileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
        const excelFileExtension = '.xlsx';
        const excelFileName = '엑셀파일명';

        const sheet1 = XLSX.utils.aoa_to_sheet(
          [
          	['컬럼명1', '컬럼명2', '컬럼명3']
          ]
        )
        
        XLSX.utils.sheet_add_aoa(
          sheet1,
          [
          	['데이터1', '데이터2', '데이터3']
          ],
          {origin:-1}
        )
        sheet1['!cols'] = [
          { wpx : 50},
          { wpx : 100},
          { wpx : 100}
        ]
        
        
        
        const workbook = {Sheets: {'시트1':sheet1}, SheetNames:['시트1']};
    	const excelButter = XLSX.write(workbook, { bookType: 'xlsx', type: 'array'});
    	const excelFile = new Blob([excelButter], { type: excelFileType});
    	FileSaver.saveAs(excelFile, excelFileName + excelFileExtension);
    }
    return(
        <>
            <button type='button' onClick={()=> excelDownload()}>
            	엑셀다운로드
            </button>
        </>
    )
}
export default Excel;

결과

기본적인 순서는 먼저 시트를 만들어준 후, 시트안에 내용을 채워주고, 만들어진 시트들을 워크북으로 묶어준 후 버퍼를 통해 파일을 다운로드한다.

 

시트에 데이터를 넣을때 aoa (array of array / 배열안의 배열) 모양으로 집어넣는것을 볼 수 있는데,

간단하게 바깥 배열 은 row를, 안쪽 배열은 column을 나타낸다고 생각하면 편하다.

 

위 사진을 배열로 나타내보면

[
    ['컬럼명1',  '컬럼명2',  '컬럼명3'],
    ['데이터1',  '데이터2',  '데이터3']
]

이런 형태의 배열로 표현할 수 있다.

 

aoa_to_sheet : aoa를 시트로 바꿔주는 함수

먼저 시트의 가장 위쪽에 컬럼의 속성을 나타낼 컬럼명을 집어넣어준다.

 

sheet_add_aoa : 시트에 배열을 추가하는 함수

첫번째 파라미터로 배열이 추가될 시트,

두번째 파라미터로 추가할 배열을 넣어준다.

 

그 아래 wpx는 각 컬럼의 width를 설정해주는 코드, 위 sheet js의 문서를 보면 행 높이 등의 속성을 찾을 수 있다.

 

const workbook = {Sheets: {'시트1':sheet1}, SheetNames:['시트1']};

만들어진 시트들을 하나의 워크북으로 묶어준다.

이전에 작성한 리액트 엑셀 다운로드 글을 보면

시트들이 담겨있는 객체는 키값으로 시트 이름을 가지고 있기 때문에

시트이름들이 담긴 배열에서 인덱스를 통해 시트이름을 가져온 후, 이를 이용해 원하는 시트를 가져왔었다.

마찬가지로 하나의 워크북으로 묶을 때, 시트 이름과 시트를 매핑해준 후, 시트배열에 시트 이름을 나열해준다.

 

이후는 버퍼로 변환 및 파일다운로드

 

 


2. 객체 및 여러개의 시트

보통 리액트는 state를 활용해 여러 객체를 다룬다.

 

import React from 'react'
import * as XLSX from 'xlsx'
import * as FileSaver from "file-saver"

const Excel = () => {
	const fruit = [
    	{'이름':'사과', '가격':3000, '수량':2},
        {'이름':'바나나', '가격':2000, '수량':1},
        {'이름':'딸기', '가격':1000, '수량':5}
    ]
	
    const car = [
    	{'종류':'세단', '바퀴':4},
        {'종류':'오토바이', '바퀴':2}
    ]

	const excelDownload = () => {
        const excelFileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
        const excelFileExtension = '.xlsx';
        const excelFileName = '엑셀파일명';

        const sheet1 = XLSX.utils.aoa_to_sheet(
          [
          	['이름', '가격', '수량']
          ]
        )
        
        const mutSheet1Row = [];
        fruit.forEach(function(item, index){
        	mutSheet1Row.push(
            	[ item['이름'], item['가격'], item['수량'] ]
            )
        })
        
        XLSX.utils.sheet_add_aoa(
          sheet1,
          mutSheet1Row,
          {origin:-1}
        )
        
        
        const sheet2 = XLSX.utils.aoa_to_sheet(
          [
          	['종류', '바퀴']
          ]
        )
        
        const mutSheet2Row = [];
        car.forEach(function(item, index){
        	mutSheet2Row.push(
            	[ item['종류'], item['바퀴'] ]
            )
        })
        
        XLSX.utils.sheet_add_aoa(
          sheet2,
          mutSheet2Row,
          {origin:-1}
        )
        
        
        
        const workbook = {Sheets: {'과일':sheet1, '차':sheet2}, SheetNames:['과일','차']};
    	const excelButter = XLSX.write(workbook, { bookType: 'xlsx', type: 'array'});
    	const excelFile = new Blob([excelButter], { type: excelFileType});
    	FileSaver.saveAs(excelFile, excelFileName + excelFileExtension);
    }
    return(
        <>
            <button type='button' onClick={()=> excelDownload()}>
            	엑셀다운로드
            </button>
        </>
    )
}

export default Excel;

 

728x90
반응형

'Library > React' 카테고리의 다른 글

리액트 엑셀 업로드  (0) 2023.04.28
fetch 페치란  (0) 2023.03.29
axios 액시오스란  (0) 2023.03.29
리액트 DB데이터로 메뉴 트리뷰 만들기  (0) 2023.03.29
리액트 페이징 처리  (0) 2023.03.29