You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中无需存盘生成并上传XLSX文件的实现方案

Node.js 生成XLSX并直接上传(无需保存到磁盘)

完全可以不用把文件写到磁盘再读取,直接用XLSX.write()生成Buffer,然后直接添加到FormData里即可,具体实现如下:

修改后的核心代码

把你原来的这两行:

XLSX.writeFile(wb, 'abc.xlsx', {compression:true});
form.append('file', fs.createReadStream('abc.xlsx'));

替换成:

// 生成XLSX的Buffer数据
const xlsxBuffer = XLSX.write(wb, { type: 'buffer', compression: true });
// 直接将Buffer添加到FormData,同时指定文件名和MIME类型
form.append('file', xlsxBuffer, {
  filename: 'abc.xlsx',
  contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});

完整示例代码

import FormData from 'form-data';
import XLSX from 'xlsx';

const form = new FormData();
const data = [['a','b'],[1,2]];
const ws = XLSX.utils.aoa_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

// 直接生成Buffer并添加到FormData
const xlsxBuffer = XLSX.write(wb, { type: 'buffer', compression: true });
form.append('file', xlsxBuffer, {
  filename: 'abc.xlsx',
  contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});

// 后续可以用form进行上传,比如用axios:
// import axios from 'axios';
// axios.post('你的上传接口地址', form, { headers: form.getHeaders() });

说明

  • XLSX.write()的type参数指定为'buffer'时,会直接返回文件的Buffer数据,不需要写入磁盘
  • FormData的append方法支持直接传入Buffer作为文件内容,通过第三个参数的filename和contentType可以让服务端正确识别文件类型和名称
  • 这样既节省了磁盘IO操作,也简化了代码流程

内容的提问来源于stack exchange,提问作者user433342

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 14:04:51