vue.js/vue.js 라이브러리

[vue.js] sheetjs 라이브러리를 이용하여 엑셀(excel) 업로드 및 읽기 예제

반응형

서론

지난번에 sheetjs 라이브러리를 이용하여 엑셀 다운로드(출처 : https://hjh0827.tistory.com/67) 를 적용했었다.

이번 프로젝트에서 엑셀 내용을 읽어서 이메일 주소 목록을 가져와 달라는 요청이 있어 동일 라이브러리를 이용하여 엑셀 업로드 및 읽기를 정리하겠다.

소스

html

<template>
  <div class="text-center">
    <input type="file" ref="excelUpload" @change="excelUpload" />
  </div>
</template>

설명

input : type = file 선언. ref 선언. input 변경시(change) 메소드 선언.

script

<script>
export default {
  methods: {
    excelUpload() {
      const xlsx = require("xlsx");
      const fileInfo = this.$refs.excelUpload.files[0];

      let reader = new FileReader();

      reader.onload = function () {
        const fileData = reader.result;
        const wb = xlsx.read(fileData, { type: "binary" });

        // sheet 개수 반복문
        // wb.SheetNames.forEach(function(sheetName) {
        //   const rowObj = xlsx.utils.sheet_to_json(wb.Sheets[sheetName]);
        //   console.log(JSON.stringify(rowObj));
        // });

        // sheet1만 사용
        const toJson = xlsx.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
        console.log(JSON.stringify(toJson));

        const toTxt = xlsx.utils.sheet_to_txt(wb.Sheets[wb.SheetNames[0]]);
        console.log(toTxt);

        const toHtml = xlsx.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
        console.log(toHtml);
      };

      reader.readAsBinaryString(fileInfo);
    },
  }
};
</script>

설명

메소드

excelUpload : 

const xlsx = require("xlsx");

> xlsx 라이브러리 선언

 

const fileInfo = this.$refs.excelUpload.files[0];

> excelUpload 에 업로드한 files 정보

 

const toJson = xlsx.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
console.log(JSON.stringify(toJson));
const toTxt = xlsx.utils.sheet_to_txt(wb.Sheets[wb.SheetNames[0]]);
console.log(toTxt);
const toHtml = xlsx.utils.sheet_to_html(wb.Sheets[wb.SheetNames[0]]);
console.log(toHtml);

> xlsx 엑셀 데이터 읽는 방법 테스트

 

reader.readAsBinaryString(fileInfo);

> 업로드한 files 정보 read

확인

 

xlsx.utils.sheet_to_json 콘솔 로그

xlsx.utils.sheet_to_txt 콘솔 로그 

xlsx.utils.sheet_to_html 콘솔 로그

반응형