axios请求、 Excel 表格导出

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浏览器下载
                // 创建a标签
                const link = document.createElement('a');
                // 规定下载的超链接
                link.setAttribute('download', `${fileName}.xls`);
                // 未点击前隐藏a链接
                link.style.display = 'none';
                // 创建URL对象,指向该文件url
                link.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 表格

你可能感兴趣的:(excel,javascript,前端)