首先导入xlsx库
import * as XLSX from 'xlsx';
表格数据示例
// 后端获取表格数据
const filteredData = ref([]);
// 数据列
const columns = [
{
title: '用户名',
dataIndex: 'username',
key: 'username'
},
{
title: '年龄',
dataIndex: 'age',
key: 'age'
},
{
title: '性别',
dataIndex: 'gender',
key: 'gender'
}
]
数据导出方法
// 将数据导出成excel
const exportData = () => {
// 数据为空时直接返回
if (!filteredData.value.length) {
return;
}
// 生成表头
const headers = columns.map(col => col.title);
const keys = columns.map(col => col.dataIndex);
// 生成数据
const data = filteredData.value.map(row => {
return keys.map(key => row[key] !== undefined ? row[key] : '');
});
// 组合表头和数据
const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data]);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, '用户详情数据');
// 导出 Excel
XLSX.writeFile(workbook, '用户详情数据.xlsx');
};