vue中下载excel文件4种方法

4,067 阅读2分钟

1.通过url下载

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

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

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

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

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

  • 这两种使用方法的不同: 

  •  window.location:当前页跳转,也就是重新定位当前页;只能在网站中打开本网站的网页。 

  •  window.open:在新窗口中打开链接;可以在网站上打开另外一个网站的地址

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

  • 就是在vue里,通过axios去调取接口,然后将返回数据处理后作为excal下载

       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 设置文件名时,可以直接设置扩展名,如果没有设置浏览器将自动检测正确的文件扩展名并添加到文件 

  •  我用过这种,直接复制到vue项目中,稍微修改一下指定的名称就能直接用

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)
    })
  • 在这里 fileDownload(res.data, this.fileName),我们指定了下载名称this.fileName,如果是固定的格式,我们也可以直接写死,比如 fileDownload(res.data, "测试.excal"), 如果我们没有指定名称和类型,下载下来就是一个没有类型的文件

  • 经过我自己的使用,有两个点需要注意,第一,fileDownload(res.data, this.fileName)中的res.data不是固定写法,一般来说后端会将返回信息封装在res.data中,也有可能没有封装,这个时候就是fileDownload(res, this.fileName)

  • 第二,如果下载的是post请求,可能会有错误,我自己使用的时候,能正常下载,但是下载的问题不是文件损坏就是空白,找了好久无法解决,最后让后端将下载的接口从post改成了get请求,就正常了

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();
      });
      }