const exportex = () => {const loading = ElLoading.service({lock: true,text: '文件导出中...',background: 'rgba(0, 0, 0, 0.7)',});try {const exportData = tableData.value.map(item => ({...item,createdAt: item.createdAt ? new Date(item.createdAt) : null}));exportExcel(exportData,tableColumns.value.filter(col => col.show),'下载文件名','标题名');} catch (error) {ElMessage.error('导出失败,请重试');} finally {loading.close();}
}
import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';
export const exportExcel = (tableData, columns, fileName, sheetTitle) => {const workbook = new ExcelJS.Workbook();const worksheet = workbook.addWorksheet('Sheet1');const enhancedColumns = [{prop: 'index',label: '序号',show: true,width: '80' },...columns];enhancedColumns.forEach((col, index) => {const width = col.width ? Number(col.width.replace('px', '')) / 8 : 15;worksheet.getColumn(index + 1).width = width; });const titleStyle = {font: { bold: true, size: 16 },alignment: { vertical: 'middle', horizontal: 'center' }};const headerStyle = {font: { bold: true, size: 12 },alignment: { vertical: 'middle', horizontal: 'center' },border: {top: { style: 'thin' },left: { style: 'thin' },bottom: { style: 'thin' },right: { style: 'thin' }}};const cellStyle = {alignment: { vertical: 'middle', horizontal: 'center' },border: {top: { style: 'thin' },left: { style: 'thin' },bottom: { style: 'thin' },right: { style: 'thin' }}};const titleRow = worksheet.addRow([sheetTitle]);titleRow.height = 30; titleRow.eachCell(cell => {cell.style = titleStyle;cell.alignment = { vertical: 'middle', horizontal: 'center' };});const lastColumn = String.fromCharCode(65 + enhancedColumns.length - 1);worksheet.mergeCells(`A1:${lastColumn}1`);const headerRow = worksheet.addRow(enhancedColumns.map(col => col.label));headerRow.eachCell(cell => cell.style = headerStyle);tableData.forEach((rowData, rowIndex) => {const rowValues = [rowIndex + 1];enhancedColumns.slice(1).forEach(col => { let value = rowData[col.prop];if (col.prop === 'createdAt' && value) {const date = new Date(value);if (isNaN(date)) {console.warn(`无效日期格式: ${value} (ID: ${rowData.id})`);value = '无效日期';} else {value = date.toLocaleString('zh-CN', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',minute: '2-digit',second: '2-digit'});}}rowValues.push(value);});const row = worksheet.addRow(rowValues);row.eachCell((cell, colNum) => {cell.style = cellStyle;});});worksheet.columns.forEach(col => {col.width = col.width || 15;});workbook.xlsx.writeBuffer().then(buffer => {const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });saveAs(blob, `${fileName}.xlsx`);});
};