element-plus el-table xlsx数据导出
时间: 2023-05-27 09:04:12 浏览: 153
要使用element-plus el-table实现xlsx数据导出,需要使用xlsx和file-saver插件。
1. 第一步是安装和引入xlsx和file-saver插件。
```
npm install xlsx file-saver --save
```
```javascript
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
```
2. 第二步是编写xlsx导出函数,该函数将读取el-table中的数据并将其写入xlsx工作表。
```javascript
export function exportExcel(tableData, fileName) {
const worksheet = XLSX.utils.json_to_sheet(tableData)
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
saveAs(new Blob([buffer], { type: 'application/octet-stream' }), fileName)
}
```
3. 最后,在事件处理程序中调用导出函数,并传递el-table数据和文件名作为参数。
```javascript
exportExcel(this.tableData, '文件名.xlsx')
```
完整示例代码:
```vue
<template>
<el-table :data="tableData" border>
<el-table-column prop="id" label="ID"></el-table-column>
<el-table-column prop="name" label="名称"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
<el-table-column prop="address" label="地址"></el-table-column>
<template slot="summary">
<el-button type="primary" @click="handleExport">导出</el-button>
</template>
</el-table>
</template>
<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
data() {
return {
tableData: [
{
id: '1',
name: '张三',
age: '20',
address: '上海'
},
{
id: '2',
name: '李四',
age: '30',
address: '北京'
},
{
id: '3',
name: '王五 ',
age: '40',
address: '广州'
}
]
}
},
methods: {
handleExport() {
const worksheet = XLSX.utils.json_to_sheet(this.tableData)
const workbook = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
FileSaver.saveAs(new Blob([buffer], { type: 'application/octet-stream' }), '数据.xlsx')
}
}
}
</script>
```
阅读全文