[FrontEnd] Vue Excel 기능

ss0510s·2022년 7월 7일
0

졸업프로젝트

목록 보기
7/9

Vue Excel 기능

목표: vue에서 버튼을 클릭할 때, 원하는 테이블을 엑셀로 다운로드 하도록 구현

  • 필요한 라이브러리 설치

    • npm을 이용하여 설치

      npm install --save xlsx

    • yarn을 이용하여 설치

      yarn add xlsx

  • html 클릭 및 테이블 구현
<!-- 테이블 생성 -->
<table id = "std_list" >
      <tr align="center" >
        <th>...</th>
        <th v-for="(value, key) in uncheckstds" v-bind:key="key">
          {{key}}
        </th>
      </tr>
      <tr v-for="stdlist in stdlists" v-bind:key="stdlist.studentIdx">
        <td>{{stdlist.name}}</td>
        <td>....</td>
        <td>....</td>
      </tr>
</table>
<!-- 버튼 클릭 이벤트-->
<button style="cursor:pointer" type = "button" id="excel_btn" @click="DownloadExcel()">EXCEL</button>
  • Vue 구현
<script>
import * as XLSX from 'xlsx' // 라이브러리 import
  ....

	methods:{
    	....
    	}, DownloadExcel() {
          	var workBook = XLSX.utils.book_new(); // 새로운 workbook 생성 
            var stdData = XLSX.utils.table_to_sheet(document.getElementById('std_list')); // table의 id를 받아서 table을 sheet로 변환한 워크시트 생성
            // var stdData = XLSX.utils.json_to_sheet(this.checkStdList); // json 객체를 sheet로 변환하여 워크시트 생성
            
            XLSX.utils.book_append_sheet(workBook, stdData, '학생출결현황'); // stdData 워크시트로 시트 생성, 해당 시트 이름 명명
            // XLSX.utils.book_append_sheet(workBook, uncheckData, '학생현황'); // 시트 추가
            XLSX.writeFile(workBook, '학생_출결_현황.xlsx'); // '학생_출결_현황.xlsx'라는 이름을 가진 파일 생성;
        },
....  
</script>
  • 결과: 웹사이트에서 보여주는 테이블의 내용을 똑같이 엑셀 파일에 넣어 다운받을 수 있다.
profile
개발자가 되기 위해 성장하는 중입니다.

0개의 댓글