前端封装post方式导出excel表格函数

接口返回文件流,前端解析

实现方式:引入axios,指定responseType值为arraybuffer,然后再回调中判断响应头content-type类型,如果是application/json,则是接口报错,这时应该抛出错误,如果是application/octet-stream,则创建a标签,模拟点击,然后销毁释放

exportExcel.js代码如下 

import axios from 'axios'
import { Message } from 'element-ui'

export function exportExcel(url, data, fileName = '下载') {
    axios.post(
        url,
        data,
        {
            responseType: 'arraybuffer'
        }
    ).then(res => {
        if (!res.data) return;
        const blob = new Blob([res.data]);
        if (res.headers['content-type'].indexOf('application/json') > -1) {
            //接口报错,没有正常返回文件流
            const reader = new FileReader();
            reader.readAsText(blob, 'utf8');
            reader.onLoad = function() {
                const response = JSON.parse(reader.result);
                if (response.error) {
                    Message({
                        type: 'error',
                        message: response.error
                    })
                }
            }
        } else if (res.headers['content-type'].indexOf('application/octet-stream')) {
            //正常返回文件流
            const a = document.createElement('a');
            a.setAttribute('download', `${fileName}.xlsx`);
            a.style.display = 'none';
            a.href = window.URL.createObjectURL(blob);
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(a.href);
            document.body.removeChild(a);
        } else {}
        
    })
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值