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/json
if (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瀏覽器下載
// 創(chuàng)建a標簽
const link = document.createElement('a');
// 規(guī)定下載的超鏈接
link.setAttribute('download', `${fileName}.xls`);
// 未點擊前隱藏a鏈接
link.style.display = 'none';
// 創(chuàng)建URL對象,指向該文件url
link.href = URL.createObjectURL(blob);
// 將a標簽添加到dom中
document.body.append(link);
// 觸發(fā)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 表格文章來源地址http://www.zghlxwxcb.cn/news/detail-506810.html
文章來源:http://www.zghlxwxcb.cn/news/detail-506810.html
到了這里,關于axios請求、 Excel 表格導出的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!