목표: vue에서 버튼을 클릭할 때, 원하는 테이블을 엑셀로 다운로드 하도록 구현
필요한 라이브러리 설치
npm을 이용하여 설치
npm install --save xlsx
yarn을 이용하여 설치
yarn add xlsx
<!-- 테이블 생성 -->
<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>
<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>