最近有个要求是写个接口,按照查询的条件将查到的数据导入到excel并返回
用的是nodejs的一个库 node-xlsx
首先将数据转变成数组集合

然后用库将数组集合转成xlsx类型的buffer,
let file = xlsx.build([{
name: '数据统计',
data: data_content
}]);
最后的步骤是设置
res的content-type,这是最重要的一点
res.set({
'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition': "attachment;filename=" + encodeURIComponent("数据统计.xlsx"),
'Pragma': 'no-cache',
'Expires': 0
});
res.send(file);
结果就是浏览器访问接口就自动下载excel了
本文介绍如何使用Node.js的node-xlsx库实现接口,将查询数据转换为Excel文件并提供下载。首先将数据转化为数组,再利用node-xlsx将其转换为xlsx缓冲区,最后设置响应头以触发文件下载。
1万+

被折叠的 条评论
为什么被折叠?



