vue中下载excel文件4种方法

本文介绍了如何通过url直接下载、利用a标签的download属性结合blob下载、js-file-download插件和fetch API进行文件下载,包括不同方法的适用场景和代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

1、通过url下载

2、通过 a 标签 download 属性结合 blob 构造函数下载

3、通过 js-file-download 插件

 4、使用fetch下载


1、通过url下载

即后端提供文件的地址,直接使用浏览器去下载

通过window.location.href = 文件路径下载

window.location.href = `${location.origin}/operation/ruleImport/template`


通过 window.open(url, '_blank')

window.open(`${location.origin}/operation/ruleImport/template`)


这两种使用方法的不同:

window.location:当前页跳转,也就是重新定位当前页;只能在网站中打开本网站的网页。
window.open:在新窗口中打开链接;可以在网站上打开另外一个网站的地址。

2、通过 a 标签 download 属性结合 blob 构造函数下载


a 标签的 download 属性是 HTML5 标准新增的,作用是触发浏览器的下载操作而不是导航到下载的 url,这个属性可以设置下载时使用新的文件名称。

前端创建超链接,接收后端的文件流:

axios.get(`/operation/ruleImport/template`, {
        responseType: "blob" //服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream',默认是'json'
    })
    .then(res => 
        if(!res) return
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据,并设置文件类型
         
        if (window.navigator.msSaveOrOpenBlob) { //兼容IE10
            navigator.msSaveBlob(blob, this.filename)
        } else {
            const href = URL.createObjectURL(blob) //创建新的URL表示指定的blob对象
            const a = document.createElement('a') //创建a标签
            a.style.display = 'none'
            a.href = href // 指定下载链接
            a.download = this.filename //指定下载文件名
            a.click() //触发下载
            URL.revokeObjectURL(a.href) //释放URL对象
        }
        // 这里也可以不创建a链接,直接window.open(href)也能下载
    })
    .catch(err => {
        console.log(err)
    })

注:请求后台接口时要在请求头上加{responseType: 'blob'};download 设置文件名时,可以直接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并添加到文件。


3、通过 js-file-download 插件


安装:

npm install js-file-download --S

使用

import fileDownload from 'js-file-download'
 
axios.get(`/operation/ruleImport/template`, {
        responseType: 'blob' //返回的数据类型
    })
    .then(res => {
        fileDownload(res.data, this.fileName)
    })

 4、使用fetch下载

      exportFile() {
          fetch('http://127.0.0.1:8765/course/exportCourse/33', {
              method: 'GET',
              headers: new Headers({
                  'Authorization': Cookie.get('Authorization') 
              }),
          })
         .then(res => res.blob())
         .then(data => {
              const blobUrl = window.URL.createObjectURL(data);
              const a = document.createElement('a');
              a.download = this.fileName+'.xlsx';
              a.href = blobUrl;
              a.click();
      });
      },

如果这4种方法,还是没有解决你下载excel文件问题,欢迎留言。

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值