React对接C# ASP.NET Core导出Excel后文件损坏无法打开怎么解决?
问题根因
你封装的Post方法在convertToJson = false时返回的是原生Fetch API的Response对象,该对象不存在value属性,因此res.value为undefined,最终构造的Blob内容为空,才会出现文件格式无效的报错。
修复方案
分两种场景可选:
方案1:不修改Post封装,直接在调用侧处理(最快修复)
调用接口拿到Response对象后,调用内置的blob()异步方法读取二进制响应内容即可,代码修改如下:
import { saveAs } from 'file-saver'; return Post(API_CREATE_CSV_POST_PRIVATE, null, model, null, null) .then(async res => { if (res.ok) { // 读取响应体为Blob对象 const rawBlob = await res.blob(); const file = new Blob( [rawBlob], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'} ); saveAs(file, "baocao.xlsx"); } })
方案2:优化Post封装,新增Blob返回支持(更通用)
先修改Post方法的定义,新增returnBlob参数适配文件导出场景:
export function Post( api, param = null, model, header = null, convertToJson = false, returnBlob = false // 新增参数,标记是否需要返回Blob格式 ) { let API = api; if (param && param.toString().length > 0) { API = API + '/' + param; } return fetch(API, { method: 'POST', headers: Header('application/json', header), body: JSON.stringify(model), }) .then(async res => { if (convertToJson && res.ok) { return res.json(); } else if (returnBlob && res.ok) { // 直接返回处理完成的Blob对象 return res.blob(); } return res; }) .catch(error => { consoleLog(error); return null; });
修改后调用导出接口时直接传入returnBlob = true即可:
import { saveAs } from 'file-saver'; // 最后一个参数传true,要求返回Blob return Post(API_CREATE_CSV_POST_PRIVATE, null, model, null, null, true) .then(file => { if (file) { const typedFile = new Blob( [file], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'} ); saveAs(typedFile, "baocao.xlsx"); } })
额外验证项
需确保ASP.NET Core后端接口返回正确:
- 接口返回类型为
FileResult/FileStreamResult,不要返回Json格式 - 响应头
Content-Type设置为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
示例后端代码参考:
public IActionResult ExportExcel([FromBody] ExportQuery query) { // 生成Excel文件字节流的逻辑 byte[] excelData = _excelService.GenerateXlsx(query); return File(excelData, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); }
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

