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

Node.js中本地Excel文件转Blob遇类型不兼容错误求助

如何将本地Excel文件转换为Blob?

我正在读取本地Excel文件,并尝试将其转换为Blob。当前使用的代码如下:

const data = fs.readFileSync('./mybook.xlsx', {encoding:'base64'});
const base64 = base64ToBlob(data)
const blob = new Blob(base64, {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});

运行后出现如下错误:

Argument type Blob is not assignable to parameter type BlobPart[] | undefined
Type Blob is not assignable to type BlobPart[]
Type Blob is not assignable to type Array

请问是否可以实现该转换?


当然可以实现,问题出在代码逻辑的冗余和参数类型不匹配上:

  1. 错误根源:base64ToBlob的返回值已经是一个Blob对象,但你又把它传给new Blob()构造函数——而Blob构造函数的第一个参数要求是BlobPart数组(如字符串、ArrayBuffer、TypedArray等),直接传Blob对象自然会触发类型不匹配错误。

  2. 两种可行修正方案:

方案一:直接复用base64ToBlob的结果

如果base64ToBlob能正确生成对应MIME类型的Blob,无需再调用new Blob():

const data = fs.readFileSync('./mybook.xlsx', {encoding:'base64'});
// 确保base64ToBlob支持传入MIME类型参数,或内部已正确设置类型
const blob = base64ToBlob(data, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

方案二:手动从Buffer转换为Blob(无需依赖base64ToBlob)

直接读取文件为Buffer再转ArrayBuffer,是更高效的方式:

const fs = require('fs');

// 直接读取文件为Buffer
const buffer = fs.readFileSync('./mybook.xlsx');
// 将Node.js Buffer转换为标准ArrayBuffer
const arrayBuffer = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
// 基于ArrayBuffer创建Blob
const blob = new Blob([arrayBuffer], {
  type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:03:32