cd front-end/vue

Vue에서 Excel 다운로드 하는 법 1. (SheetJS)

성덕 2022. 1. 21. 11:24

Vue에서 엑셀 다운로드 하는 방법은 여러가지가 있는 것으로 보인다. 

그 중 오늘은 SheetJS 라이브러리를 사용하는 방법을 기록해 보겠다. 

SheetJS NPM 설치

npm i xlsx --save

Data

sample data는 json 형식, header와 body를 나눠서 관리함.

// assets/js/data.js

export const excelData = {
  header: [['이름', '칼로리', '지방', '탄수화물', '단백질', '철분']],
  body: [
    {
      name: '바나나',
      calories: 159,
      fat: 6.0,
      carbs: 24,
      protein: 4.0,
      iron: '1%',
    },
    {
      name: '사과',
      calories: 237,
      fat: 9.0,
      carbs: 37,
      protein: 4.3,
      iron: '1%',
    },
    ...
}

 

JS

header는 별도 셋팅 해줘야 하며, header array를 add하는 방법으로 적용 하였다. 

// plugins/excel.js

import xlsx from 'xlsx';

// 엑셀 다운로드
function downloadExcelFile(data, fileName, sheetName) {
  const workBook = xlsx.utils.book_new();

  const workSheet = xlsx.utils.json_to_sheet(data.body);
  xlsx.utils.sheet_add_aoa(workSheet, data.header); // header set

  xlsx.utils.book_append_sheet(workBook, workSheet, sheetName);
  xlsx.writeFile(workBook, fileName);
}

export { downloadExcelFile };

 

Vue 에서의 사용

<script>
import { downloadExcelFile } from '@/plugins/excel';
import { excelData } from '@/assets/js/data';

export default {
  methods: {
    // 엑셀 다운로드
    downloadFile() {
      downloadExcelFile(excelData, 'sampleFile.xlsx', 'sampleSheet');
    },
  },
};
</script>

결과

엑셀파일 다운로드 결과

header set 코드 미포함 시 화면은 아래와 같다. json key 이름으로 표기되는 것으로 보인다.

 

다음은 SheetJS의 style 입히는 것과 file-saver 를 함께 적용하는 글을 포스팅 하고자 한다.