1、安装需要的插件
cnpm i xlsx -S
cnpm i file-saver -S
2、在vue中引入
<template>
<div>
<el-button type="primary" icon="el-icon-download" @click="handleDaochu">导出</el-button>
</div>
</template>
<script>
// 导入插件
import * as XLSX from "xlsx";
import { saveAs } from "file-saver";
export default {
// 标识,当前组件的名称
name: "user",
data() {
return {
tableData: [
{
name: "张三",
},
],
};
},
methods: {
handleDaochu() {
// 创建一个workbook
const workbook = XLSX.utils.book_new();
// 导出数据
const worksheet = XLSX.utils.json_to_sheet(this.tableData);
XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet 1");
// 将workbook转为二进制数据
const excelData = XLSX.write(workbook, {
type: "array",
bookType: "xlsx",
});
// 创建blob对象并保存excel文件
const blob = new Blob([excelData], { type: "application/octet-stream" });
// 设置导出文件名字
saveAs(blob, "data.xlsx");
},
},
};
</script>