1.安装 xlsx 库
npm install xlsx
2.创建导出函数
src/utils/excelUtils.js
import * as XLSX from 'xlsx';
const exportToExcel = (fileName, datas, sheetNames) => {
// 创建工作簿
const wb = XLSX.utils.book_new()
for (let i = 0; i < datas.length; i++) {
let data = datas[i];
let sheetName = sheetNames[i];
// 创建工作表
let ws = XLSX.utils.json_to_sheet(data)
// 将工作表放入工作簿中
XLSX.utils.book_append_sheet(wb, ws, sheetName)
}
// 生成文件并下载
XLSX.writeFile(wb, fileName)
}
export default exportToExcel;
3.在组件中调用导出函数
<template>
<div>
<el-button @click="exportExcel">导出 Excel</el-button>
</div>
</template>
<script lang="ts">
import exportToExcel from '@/utils/excelUtils';
const exportExcel = () => {
const data2 = [
{ name: 'Alice', age: 25, occupation: 'Engineer' },
{ name: 'Bob', age: 30, occupation: 'Designer' },
{ name: 'Carol', age: 28, occupation: 'Developer' }
];
const data3 = [
{ name2: 'Alice', age: 27, occupation: 'Engineer' },
{ name2: 'Bob', age: 31, occupation: 'Designer' },
{ name2: 'Carol', age: 29, occupation: 'Developer' }
];
exportToExcel('user_data.xlsx', [data2, data3], ['Sheet1', 'Sheet_data3']);
};
export default {
methods: {
exportExcel
}
};
</script>