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

使用ExcelJS将API返回数组写入Excel文件失败求助

问题修复方案

你的代码存在两个核心问题,导致无法将API返回的res数组写入Excel:

  1. 变量作用域与异步顺序问题:res是自执行异步函数内部的局部变量,外部Excel操作代码无法访问;且异步函数执行滞后,Excel代码会先运行,此时res还未被赋值。
  2. 目标行错误:当前代码操作的是第3行,而你需要写入的是第2行(从A2开始)。

以下是修正后的完整代码:

const api2 = require("fordonsuppgifter-api-wrapper");
const Excel = require('exceljs');

const fileName = 'simple.xlsx';

(async () => {
    console.log("fetching vehicle info");
    // 等待API返回数据
    const res = await api2.GetVehicleInformation("XMP433");
    console.log(res);

    // 初始化Excel工作簿和工作表
    const wb = new Excel.Workbook();
    const ws = wb.addWorksheet('My Sheet');

    // 获取第2行,将res数组元素依次填入A2、B2...单元格
    const row2 = ws.getRow(2);
    row2.values = res;

    // 写入文件并处理结果
    await wb.xlsx.writeFile(fileName);
    console.log('file created');
})().catch(err => {
    console.log(err.message);
});

关键改动说明:

  • 将Excel操作逻辑全部移入异步函数内部,确保拿到res数据后再执行写入
  • 用ws.getRow(2)定位到需求的第2行,直接把res数组赋值给row2.values,数组元素会自动对应A2、B2等单元格
  • 统一用await处理异步操作,通过外层catch捕获API请求和文件写入的所有错误

如果API返回的res是对象而非纯值数组,需要先转换为值数组:

row2.values = Object.values(res);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 14:55:20