如何使用SheetJS下载后端返回的Excel文件?
解决SheetJS无法处理后端Excel文件及页面卡死问题
问题根源
你的代码存在两个核心问题:
- axios请求未指定
responseType,导致后端返回的二进制Excel文件被解析为字符串,生成的Blob无效,SheetJS无法识别这种错误格式的内容,进而引发页面卡死。 - 混淆了「直接下载文件」和「用SheetJS处理文件」的逻辑:如果只是下载,无需SheetJS;如果需要解析后再导出,才需要用到SheetJS。
解决方案
方案1:直接下载后端返回的Excel文件(无需SheetJS)
修正axios请求,指定responseType: 'blob',直接处理二进制流:
// 替换你的axios请求,确保设置responseType axios({ method: 'post', // 或对应请求方法 url: '你的接口地址', // 替换为实际接口 data: datos, responseType: 'blob' // 关键:指定返回类型为Blob }).then((res) => { const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = 'demo.xlsx' a.click() // 释放URL对象,避免内存泄漏 URL.revokeObjectURL(a.href) })
方案2:用SheetJS解析后端文件后再导出
如果需要先解析Excel内容(比如修改数据)再导出,先把后端返回的二进制流传给SheetJS处理:
axios({ method: 'post', url: '你的接口地址', data: datos, responseType: 'arraybuffer' // 用arraybuffer更适合SheetJS读取 }).then((res) => { // 用SheetJS读取二进制内容 const workbook = XLSX.read(new Uint8Array(res.data), { type: 'array' }) // 这里可以对workbook进行修改,比如修改工作表数据 // const worksheet = workbook.Sheets[workbook.SheetNames[0]] // XLSX.utils.sheet_add_aoa(worksheet, [['新数据']], { origin: 'A1' }) // 生成Excel文件并下载 const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' }) const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }) const a = document.createElement('a') a.href = URL.createObjectURL(blob) a.download = 'processed_demo.xlsx' a.click() URL.revokeObjectURL(a.href) })
额外注意事项
- 确认后端返回的是合法的.xlsx文件:如果后端返回的是错误格式(比如HTML错误页),SheetJS也会无法处理导致卡死,可通过直接在浏览器访问接口地址验证文件是否正常。
- 避免内存泄漏:每次调用
URL.createObjectURL后,记得用URL.revokeObjectURL释放资源。
内容的提问来源于stack exchange,提问作者Kuro Nameless
相关产品推荐
相关产品推荐

