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

使用google-spreadsheet开发WP Bot向谷歌表格添数据时触发addRows未定义错误

问题排查:google-spreadsheet包调用addRow时出现TypeError错误

我开发了一款向谷歌表格添加数据的WP Bot,使用google-spreadsheet npm包,运行时触发如下错误:

TypeError: Cannot read properties of undefined (reading 'addRows')
at new Promise ()
at addRow (node:internal/util:350:12)
at accessSpreadsheet (C:\Users\user\Desktop\wpbott\index1.js:36:36)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
错误代码位置:\node_modules\google-spreadsheet\lib\GoogleSpreadsheetWorksheet.js 中 const rows = await this.addRows([rowValues], options); 行

相关代码

const addDataToSheet = async (sheetId, data) => {
    const doc = new GoogleSpreadsheet(sheetId);
    async function accessSpreadsheet() {
        await doc.useServiceAccountAuth({
        client_email: creds.client_email,
        private_key: creds.private_key,
        });
    await doc.loadInfo(); 
    const sheet = doc.sheetsByIndex[0];
    console.log(doc.title); 
    console.log(sheet.title);
    console.log(sheet.rowCount);
    const rowValues = Object.values(data);
    const addRow = promisify(sheet.addRow)
    await promisify(sheet.addRow)(rowValues);
    }
accessSpreadsheet();
};

调用代码

await addDataToSheet('1mbvrmGbwZBlPYaYSf-Ftoeoz9Jirhmeg1HmLre_KlQ4',{
      Name: userData[from].Name,
      Age: userData[from].Age,
      Gender: userData[from].Gender
    });

错误原因

  1. promisify滥用:google-spreadsheet v4+版本中,sheet.addRow本身已是异步Promise函数,无需用util.promisify包装。强行包装会破坏函数的this上下文,导致this指向undefined,调用this.addRows时触发错误。
  2. 异步函数未等待:accessSpreadsheet()是异步函数,但在addDataToSheet中直接调用未加await,会导致函数提前结束,可能引发后续逻辑异常。

修复方案

修改代码如下:

const addDataToSheet = async (sheetId, data) => {
    const doc = new GoogleSpreadsheet(sheetId);
    async function accessSpreadsheet() {
        await doc.useServiceAccountAuth({
            client_email: creds.client_email,
            private_key: creds.private_key,
        });
        await doc.loadInfo(); 
        const sheet = doc.sheetsByIndex[0];
        console.log(doc.title); 
        console.log(sheet.title);
        console.log(sheet.rowCount);
        // 直接使用原生addRow,传入原始对象(自动匹配表头)
        await sheet.addRow(data);
    }
    // 等待异步逻辑执行完成
    await accessSpreadsheet();
};

额外说明

  • google-spreadsheet v4版本API已全面Promise化,所有异步操作均返回Promise,无需再用promisify处理。
  • sheet.addRow接受对象参数(键对应表格表头),无需将数据转为数组,这样能保证数据与表头正确映射。

内容的提问来源于stack exchange,提问作者Mahammed Sarfaraz Nawaz Pagala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 21:37:08