如何将JSReport返回的html-to-xlsx响应转换为可下载的Excel文件
问题根因
JSReport的html-to-xlsx接口返回内容为Excel文件的二进制流,你的代码未配置axios的响应类型,axios默认按UTF-8文本解析二进制数据,最终输出为乱码。
修复方案
修改axios请求配置,指定响应按二进制格式接收,收到数据后直接写入本地文件即可生成可正常打开的Excel表格,参考代码如下:
const axios = require("axios"); const fs = require("fs"); const url = "http://localhost:5488/api/report/"; axios.post(url, { "template": { "shortid": "2_Kw0BRuOm", "recipe": "html-to-xlsx", "data": { "people": [ { "name": "Omar rafat", "age": "20", "job": "Software Engineer" } ] }, "options": { "reports": { "save": true } } } }, { // 关键配置:指定响应类型为二进制数组,避免axios自动转文本 responseType: 'arraybuffer' }).then(res => { // 将二进制流直接写入后缀为.xlsx的文件 fs.writeFileSync('./导出结果.xlsx', res.data); console.log('Excel导出成功,文件已保存到当前运行目录'); }).catch(err => console.log('导出失败:', err));
额外说明
- 若在浏览器端调用该接口,可将
responseType设置为blob,后续通过URL.createObjectURL生成临时下载链接触发浏览器下载即可,无需使用文件系统模块。 - 你代码中提前定义的data变量未被使用,可按需清理冗余代码。
内容的提问来源于stack exchange,提问作者Okira
相关产品推荐
相关产品推荐

