vue导出excel及报错处理

根据后端返回文件流导出excel

思路:先封装方法导出方法---在项目封装好的axios请求中加入responseType: 'blob'---在页面中使用

步骤一

在utils中创建一个tool.js文件,并粘入以下代码

export function exportFile(data, type, fileName) {
    const blob = new Blob([data], {
        // type类型后端返回来的数据中会有,根据自己实际进行修改
        // 表格下载为 application/xlsx,压缩包为 application/zip等,
        type: type
    })
    const filename = fileName
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
    } else {
        var blobURL = window.URL.createObjectURL(blob)
        // 创建隐藏<a>标签进行下载
        var tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)// 移除dom元素
        window.URL.revokeObjectURL(blobURL)// 释放bolb内存
    }
}

步骤二

在封装好的axios中加入responseType: 'blob'

步骤三

先引入刚封装好的方法

import {exportFile} from '@/utils/tool.js'

页面使用 可以写一个button按钮绑定一个点击事件函数,然后调用请求

 
<el-button @click="getExcel"></el-button>




getExcel(){
  const params = get请求的参数

    getStadiumNeedUserExport(params).then(res => {
         console.log(res);
        const name = res.headers['content-disposition']//获取后台返回文件名
        let b = name.lastIndexOf("=") //截取
        let fileName = name.substring(b + 1, name.length);//下载后文件名
        console.log(fileName);
        const contentType =
          'application/vnd.ms-excel'
        exportFile(res.data, contentType, fileName)
      })
}

注意:下载后的文件名要与后台返回文件名一致(主要后缀名要一致,否则下载后的文件打不开)

这里直接用后台返回数据名进行截取

步骤四

然后点击button就可以下载Excel啦~

可能的报错处理

1、被封装的请求拦截器拦截了

解决办法

判断文件类型,如果为后台返回的文件类型,则不进行拦截

if (res.headers['content-type'] === "application/x-xls") {
      return res
    }

2、下载文件类型与后台返回数据类型保持一致

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值