el-table导出excel

流程:1.调用后端接口>>>>2.接口返回文件流>>>>>>3.下载文件

1.数据格式化

导出接口后端返回是文件流,所以接口需要加responseType: 'blob'参数,另外使用transformResponse对文件流数据格式化

  exportUnitLog: {
    url: '/unitlog/export',
    responseType: "blob",
    transformResponse(res) {
      const returnRes = res
      // 解析错误
      if (returnRes.type === 'application/json') {
        return {
          success: true,
          data: returnRes,
        }
      }
      return {
        success: true,
        code: 0,
        data: res,
        message: '',
      }
    },
  },

2.调用接口

    async exportLog() {
      const data = {
        //参数
      }
      await service.exportUnitLog(data).then((res) => {
        this.downloadCallback(res, '测点匹配失败日志.xlsx'); // 调用下载函数
      })
    },

3.下载

    //生成下载文件
    downloadCallback(res, fileName) {
      const content = res
      const blob = new Blob([content])
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    },

发表评论 / Comment

用心评论~