通过文件流方式导出下载excel文件

913 阅读1分钟

有时候会有下载excel的需求,如果后端直接给链接,我们下载就很方便

  downLoadByLink(link: string) {
    const CreateA = document.createElement('a')
    CreateA.href = link
    CreateA.download = ''
    document.body.appendChild(CreateA)
    CreateA.click()
    document.body.removeChild(CreateA)
  }
}

但是大部分情况是按需下载,实时下载,前端选择需要下载的数据,后端返回数据流,然后我们处理后导出

  • 首先,请求方法需要修改
// axios 插件
// 在请求头中增加下面代码
responseType: 'blob'
  • 其次, 返回数据要单独处理
if (response.headers && response.headers['content-disposition']) {
  // 文件流下载excel
  return response
}
  • 最后,对返回的response数据进行加工后导出
/**
 * @description 通过文件流方式导出下载excel文件
 * @param {any} response 接口返回的数据
*/
function downloadFile(response) {
  const str = decodeURIComponent(data.headers['content-disposition'])
  const fileName = str.split('filename=')[1]
  const content = data.data
  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)
  }
}