vue-element-admin项目中将el-table中的数据导出成excel
问题描述
使用vue-element-admin开发过程中需要将el-table中的数据导出为excel
问题解决
- 安装库
npm i file-saver xlsx -S
- 引入库
import FileSaver from 'file-saver'
// full import
import * as XLSX from 'xlsx';
// named imports
import { write, utils } from 'xlsx';
- vue文件
<el-button type="primary" @click="handleDownload('demo')">下载excel</el-button>
<el-table id="excel_table" :data="tableData">
<el-table-column label="序号" type="index"></el-table-column>
<el-table-column label="ID" prop="id"></el-table-column>
<el-table-column label="规则" prop="rule"></el-table-column>
<el-table-column label="类型" prop="type"></el-table-column>
<el-table-column label="状态" prop="status"></el-table-column>
<el-table-column label="权重" prop="priority"></el-table-column>
<el-table-column label="描述" prop="description"></el-table-column>
</el-table>
- 导出方法
handleDownload(name) {
let table = document.getElementById("excel_table")
let et = utils.table_to_book(table)
let output = write(et, {
bookType: "xlsx",
bookSST: true,
type: "array"
})
try {
FileSaver.saveAs(new Blob([output], { type: "application/octet-stream" }), `${name}.xlsx`)
} catch (e) {}
return output
}