import axios from 'axios';//用于导出excel表格
export const exportExcel = ({ method = 'get', url, data = {}, fileName }) => {const field = method === 'get' ? 'params' : 'data';axios({method,url,[field]: data,responseType: 'blob'}).then((res) => {//导出接口失败 返回的也是blob type为application/jsonif (res.data?.type === 'application/json') throw new Error();const blob = new Blob([res.data], {type: 'application/vnd.ms-excel'});if ('download' in document.createElement('a')) {// 非IE浏览器下载// 创建a标签const link = document.createElement('a');// 规定下载的超链接link.setAttribute('download', `${fileName}.xls`);// 未点击前隐藏a链接link.style.display = 'none';// 创建URL对象,指向该文件urllink.href = URL.createObjectURL(blob);// 将a标签添加到dom中document.body.append(link);// 触发a标签点击事件link.click();// 释放之前的URL对象URL.revokeObjectURL(link.href);// 从dom中移除该a链接document.body.removeChild(link);} else {// IE10+ 下载navigator.msSaveBlob(blob, filename);}console.log('导出成功');}).catch(() => {console.log('导出失败');});
};
注:基于axios 直接请求后端接口,导出Excel 表格