美文网首页
vue中使用post导出excel的一次糟心记录

vue中使用post导出excel的一次糟心记录

作者: 哑巴湖大水怪吖 | 来源:发表于2022-07-26 16:32 被阅读0次

因为这次要导出的excel数据有点复杂,并且使用的是post请求,所以跟以前的导出做的不一样,

然后说一下自己遇到的问题吧,返回的数据是乱码,然后因为后端无论怎么样都会有返回,所以我封装的请求无法得到 res.code === 200 永远走的都是catch里面,然后我找了半天才发现原因,一直以为是我获取数据是乱码的问题,然后一直认为自己的responseType:'blob'没作用,找了各种问题,最后才找到所在,就单纯记录一下,然后这个下载的方法我直接到网上找的

 // 日报告导出
     async datTimeExport(){
      let form1 = {
              type:1,
              ids:[24,26],
              date:"2022-07-23",          
              }
      try {
          const data = await this.$http.exportExcel('/patrol/patrol-log-export',form1,{responseType:'blob'})
          // console.log(data)
          this.download(data) // 导出excel
      } catch (error) {
        console.log(error)
      }
    },
    // 下载文件
    download (data) {
        if (!data) {
            return
        }
        window.URL = window.URL || window.webkitURL // 兼容性
        // 创建一个 URL 这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
        let url = window.URL.createObjectURL(new Blob([data])) 
        let link = document.createElement('a') // 创建一个a元素
        link.style.display = 'none' // 让a元素在页面中隐藏
        link.href = url // 绑定 a 元素的 href 为当前的url
        link.setAttribute('download', 'excel.xlsx') // 设置 a 元素的属性
        document.body.appendChild(link) // 添加到页面中
        link.click() // 点击a元素 下载excel文件
        window.URL.revokeObjectURL(url)
    },
封装的请求接口
// 文件下载导出
http.exportExcel = (url,data,config) => {
  return instance.post(url,data,config).then(res => {
        // console.log(res)
        return res
        // if(res.code === 200 ){
        //   console.log(res)
        //   return res
        // }
        // else{
        //   console.log(res)
        //   return Promise.reject(res);
        // }
  })
}

相关文章

网友评论

      本文标题:vue中使用post导出excel的一次糟心记录

      本文链接:https://www.haomeiwen.com/subject/pjboirtx.html