安装依赖
npm install xlsx
创建工具文件exportToExcel.ts
import * as XLSX from 'xlsx';interface TableData {[key: string]: any;
}type MappingFunction = (row: TableData) => { [key: string]: any };export const exportToExcel = (data: TableData[],fileName: string,mappingFunction: MappingFunction,columnWidths: { [key: string]: number }
) => {const formattedData = data.map(mappingFunction);const worksheet = XLSX.utils.json_to_sheet(formattedData);// Set column widthsconst colWidths = Object.keys(columnWidths).map((key) => ({ wch: columnWidths[key] }));worksheet['!cols'] = colWidths;const workbook = XLSX.utils.book_new();XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');XLSX.writeFile(workbook, `${fileName}.xlsx`);
};
页面使用
import { exportToExcel } from '/@/utils/exportToExcel'; //换成自己路径
const tableData = ref([
{
"user_type":1,
"created_at":"2024-07-20 17:57:48",
"user_type":"赋予用户:注册会员4ofmPbL 【1】积分"
}
])
const mapTableDataToExportFormat = (row: any) => ({交易类型: row.user_type == 1 ? '银行' : row.user_type == 2 ? '小程序用户' : '平台',发放时间: row.created_at,备注: row.remark,
});const columnWidths = {交易类型: 10,发放时间: 20,备注: 50,
};const handleExport = () => {exportToExcel(tableData.value, '积分记录', mapTableDataToExportFormat, columnWidths);
};