新建一个out_excel.js文件并调用
import * as XLSX from "xlsx";
export const exportToExcel = (tableData, tableName, sheetName, fileName) => {
const ws = XLSX.utils.aoa_to_sheet([...[tableName], ...tableData]); // tableName为表头,tableData为数据
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, sheetName); // sheetName为自定义的sheet表名
XLSX.writeFile(wb, fileName + ".xlsx"); // fileName为自定义的文件名
};
下面是vue中调用
// 导出按钮事件
<el-button type="primary" @click="outExcel">导出</el-button>
// 引入导出excel文件
import { exportToExcel } from "@/utils/out_excel.js"; // 导出表格
// 表格数据
const tableData = reactive({
arr: [
{
area: "比基尼海滩",
group: "蟹黄堡",
name: "海绵宝宝",
number: "8",
numberAll: "16.0",
time: "2020/04/18 21:52",
},
{
area: "比基尼海滩",
group: "蟹黄堡",
name: "章鱼哥",
number: "8",
numberAll: "16.0",
time: "2020/04/18 21:52",
}
],
});
// 调用事件bigArr为传入的数据,headArr为传入的表头
const outExcel = () => {
let smallArr = Array.from(tableData.arr)
let bigArr = []
smallArr = smallArr.map((item) => {
bigArr.push(Object.values(item))
})
let headArr = ['区域', '公司', '名称', '年龄', '收入', '时间']
exportToExcel(bigArr, headArr, 'sheet1', '比基尼海滩统计');
}
此时bigArr的数据的结构为
[
['比基尼海滩', '蟹黄堡', '海绵宝宝', '8', '16.0', '2020/04/18 21:52'],['比基尼海滩', '蟹黄堡', '章鱼哥', '8', '16.0', '2020/04/18 21:52']
]
最后导出的excel文件长这样