utils/exportexcel.js
import { parseTime } from '@/utils/format'; import { Message } from 'element-ui'; /** * 导出Excel文件 * @param {*} data 文件数据流 * @param {String} filePrefix 文件前缀名 * @param {String} fileSuffix 文件后缀名 */ export function exportExcel(data, filePrefix, fileSuffix) { // 判断文件前缀名是否存在,不存在默认'EXPORTEXCEL' filePrefix = filePrefix ?? 'EXPORTEXCEL'; // 判断文件后缀名是否存在,不存在默认'.xls' fileSuffix = fileSuffix ?? '.xls'; // 处理文件数据流 const contentByExportExcel = data; const blobByExportExcel = new Blob([contentByExportExcel], { type: 'application/vnd.ms-excel;charset=utf-8' }); // 组装文件名称 const filenameByExportExcel = `${filePrefix}_${parseTime( new Date(), '{y}-{m}-{d}' )}_${new Date().getTime()}${fileSuffix}`; // 执行文件下载操作 if ('download' in document.createElement('a')) { const elink = document.createElement('a'); elink.download = filenameByExportExcel; elink.style.display = 'none'; elink.href = URL.createObjectURL(blobByExportExcel); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); document.body.removeChild(elink); Message({ message: '导出Excel成功!', type: 'success', showClose: true, center: true }); } else { navigator.msSaveBlob(blobByExportExcel, filenameByExportExcel); Message({ message: '导出Excel成功!', type: 'success', showClose: true, center: true }); } }
引入:
import { exportExcel } from '@/utils/exportexcel';
使用:
// 排除不需要的属性 let { pageNum, pageSize, ...otherObj } = { ...this.queryParams }; // 发送导出请求 exportAttendanceReport({ ...otherObj }) .then((response) => { exportExcel(response, '统计表格', '.xlsx'); }) .catch(() => { this.$message.error('导出异常!'); });
需要注意的点,数据的响应类型(responseType: 'blob'),数据大概如下:
标签:文件,elink,filePrefix,导出,fileSuffix,Excel,封装 From: https://www.cnblogs.com/zaijin-yang/p/17306464.html