ReactJS实现CSV文件下载时格式异常问题求助
React中CSV下载格式异常问题求助
我在ReactJS里尝试将服务端返回的数据转换并下载为CSV文件,但文件格式出现异常。以下是我的实现代码,同时附上服务端返回内容、正确格式示例以及错误格式示例的截图说明:
实现代码
const getDownloadCSV = async (userId: number, orderId: number) => { try { const response = await downloadCSVOrder(userId, orderId) const csv = '\uFEFF' + response const encoder = new TextEncoder() const blob = new Blob([encoder.encode(csv)], { type: 'text/csv;charset=utf-8;', }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.setAttribute('href', url) link.setAttribute('download', 'filename.csv') link.style.visibility = 'hidden' document.body.appendChild(link) link.click() document.body.removeChild(link) } catch (error) { if (error instanceof AxiosError) { openNotification({ type: 'error', description: error.message }) } else { openNotification({ type: 'error', description: 'Some error occurred' }) } } }
相关截图说明
- 服务端返回内容截图:[服务端返回的原始CSV文本]、[服务端返回内容详情]
- 正确格式示例截图:[符合预期的CSV表格格式]
- 错误格式示例截图:[下载后出现格式错乱的CSV]
问题排查与修复方案
- 移除多余的TextEncoder编码
你的代码中使用TextEncoder对已有的文本进行二次编码,这会破坏原始CSV的编码格式,导致乱码或格式错乱。直接将文本内容传入Blob即可:
const getDownloadCSV = async (userId: number, orderId: number) => { try { const response = await downloadCSVOrder(userId, orderId) // 直接拼接BOM与响应文本,无需额外编码 const blob = new Blob(['\uFEFF' + response], { type: 'text/csv;charset=utf-8;' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = 'filename.csv' link.style.visibility = 'hidden' document.body.appendChild(link) link.click() document.body.removeChild(link) URL.revokeObjectURL(url) // 新增:释放URL对象,避免内存泄漏 } catch (error) { if (error instanceof AxiosError) { openNotification({ type: 'error', description: error.message }) } else { openNotification({ type: 'error', description: '发生未知错误' }) } } }
- 确保Axios请求的响应类型为文本
如果downloadCSVOrder接口默认将响应解析为JSON,会把CSV文本转换成对象,导致格式完全错误。需要在请求配置中设置responseType: 'text':
// 示例:downloadCSVOrder的Axios实现 const downloadCSVOrder = (userId: number, orderId: number) => { return axios.get('/api/your-csv-download-url', { params: { userId, orderId }, responseType: 'text' // 必须设置为文本类型 }) }
- 统一换行符适配Windows系统
部分CSV阅读器(如Excel)对换行符要求严格,需要将\n替换为\r\n才能正确识别行:
const formattedCSV = '\uFEFF' + response.replace(/\n/g, '\r\n') const blob = new Blob([formattedCSV], { type: 'text/csv;charset=utf-8;' })
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

