想要实现前端对表格中的数据进行导出,这里推荐使用xlsx这个依赖库实现。
1、安装
pnpm install xlsx
2、使用
javascript
import * as XLSX from "xlsx";
直接在组件里导入XLSX库,然后给表格table通过ref创建响应式数据拿到table实例,将实例传给XLSX.utils.table_to_book()方法,再使用XLSX.writeFile()就可以下载excel文件了。具体方法请看demo源代码。
3、demo源代码
javascript
<template>
<div class="page6">
<div style="display:flex;justify-content: flex-end">
<el-button type="primary" @click="exportExcel">导出</el-button>
</div>
<el-table ref="tableRef" :data="tableData" stripe style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</div>
</template>
<script setup>
import * as XLSX from 'xlsx'
const tableRef = ref(null)
const exportExcel = () =>{
const tableDom = tableRef.value?.$el;
if (tableDom) {
const wb = XLSX.utils.table_to_book(tableDom);
XLSX.writeFile(wb, '表格数据.xlsx');
}
}
const tableData = [
{
date: '2016-05-03',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-02',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-04',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
{
date: '2016-05-01',
name: 'Tom',
address: 'No. 189, Grove St, Los Angeles',
},
]
</script>
<style lang="less" scoped>
.page6{
width: 100%;
height: 100%;
padding: 20px;
}
</style>
4、效果
下载的excel文件