背景:需要把表格数据导出到excel
步骤:
1.安装
npm install --save xlsx file-saver
2.在导出的页面
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
3.使用(核心代码)
<template><div class="index"><el-button type="primary" @click="save">导出</el-button><!-- 导出按钮 --><!-- 表格组件 --><el-table :data="tableData" style="width: 100%" border id="el-table" ref="tableRef"><el-table-column type="selection" width="50" align="center" /><el-table-column label="姓名" prop="name" /><el-table-column label="性别" prop="age" width="180" /><el-table-column label="电话" prop="phone" width="180" /><el-table-column label="电子邮件" prop="email" width="180" /><el-table-column label="介绍" prop="introduce" width="260" /></el-table></div>
</template>
<script setup lang="ts">
// 依赖引入
import FileSaver from "file-saver";
import * as XLSX from 'xlsx'function save() {nextTick(function () {let filename = ''const xlsxParam = { raw: true } //转化成Excel使用原始格式const elTable = XLSX.utils.table_to_book(document.getElementById('el-table'), xlsxParam)filename = '导出测试.xlsx'const wbout = XLSX.write(elTable, { bookType: 'xlsx', bookSST: true, type: 'array' })try {FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), filename)} catch (e) {if (typeof console !== 'undefined') {console.log(e, wbout)}}return wbout})
}
</script>