用vue封装一个支持导出表格的el-table组件
时间: 2024-05-01 12:16:28 浏览: 119
首先需要安装xlsx和file-saver库,用于生成和下载Excel文件。
```bash
npm install xlsx file-saver -S
```
然后,在组件中引入这两个库,并在methods中定义一个exportExcel方法,用于导出表格数据为Excel文件。
```vue
<template>
<el-table :data="tableData" ref="table">
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
<el-button type="primary" @click="exportExcel">Export Excel</el-button>
</template>
<script>
import XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
data() {
return {
tableData: [
{ name: "John", age: 30 },
{ name: "Jane", age: 25 },
{ name: "Bob", age: 40 }
]
};
},
methods: {
exportExcel() {
const sheet = XLSX.utils.json_to_sheet(this.tableData);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, "Sheet1");
const excelBuffer = XLSX.write(workbook, {
bookType: "xlsx",
type: "array"
});
const excelBlob = new Blob([excelBuffer], { type: "application/octet-stream" });
FileSaver.saveAs(excelBlob, "table.xlsx");
}
}
};
</script>
```
以上代码中,我们通过XLSX.utils.json_to_sheet方法将表格数据转换为Excel表格的sheet,然后通过XLSX.utils.book_new方法创建一个新的workbook,并将sheet添加到workbook中。最后通过XLSX.write方法将workbook转换为Excel文件的二进制数据,FileSaver.saveAs方法将二进制数据保存为文件并下载到本地。
阅读全文