解决前端下载Excel文件无法打开

思路大概是这样的

  1. 文件流
  2. Blob类型
  3. URL
  4. 创建a标签
  5. 指定href为URL
  6. 设置download属性来指定文件名

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
export const downloadFile = (_blob: Blob, fileName: string) => {
const blob = new Blob([_blob], { type: 'application/vnd.ms-excel' })
const a = document.createElement('a')
a.style.display = 'none'
const href = window.URL.createObjectURL(blob)
a.href = href
a.download = fileName
document.body.append(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(href)
}

常用的excel对应得mine-type类型:
"application/vnd.ms-excel"
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

重点:在response中加上responseType: 'blob'


解决前端下载Excel文件无法打开
https://adain.top/post/19e3ffe2363f/
作者
adain
发布于
2024年1月8日
许可协议