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

使用google-spreadsheet v4.1.1时出现doc.useServiceAccountAuth不是函数错误

问题原因

你使用的google-spreadsheet是v4.1.1版本,该版本已移除useServiceAccountAuth方法——这个方法属于v3及更早版本的API,v4采用了全新的认证逻辑,调用不存在的方法因此触发TypeError。

修复方案

直接在初始化GoogleSpreadsheet实例时传入认证凭证即可,以下是两种常用实现方式:

方式一:直接传入服务账号凭证

修改初始化与认证部分代码:

async function writeToSheet(data) {
    if (data.length === 0) {
        logger.info("No data to write to the sheet.");
        return;
    }

    const creds = require('../credentials.json');
    // 初始化文档时直接传入auth参数
    const doc = new GoogleSpreadsheet("sdfadsgsdfgadsfDML-17jbHMdXkgcqWtmvJ0", {
        auth: {
            client_email: creds.client_email,
            private_key: creds.private_key,
        }
    });

    try {
        // 无需调用useServiceAccountAuth,直接加载文档信息
        await doc.loadInfo(); 
        const sheet = doc.sheetsByIndex[0];

        await sheet.addRows(data);
        logger.info("Data successfully written to the sheet.");
    } catch (error) {
        logger.error("Failed to write data to the sheet:", error);
    }
}

方式二:使用GoogleAuth实例(灵活控制认证)

如果需要自定义权限范围或其他认证参数,可借助google-auth-library创建认证实例:

const { GoogleAuth } = require('google-auth-library');

async function writeToSheet(data) {
    if (data.length === 0) {
        logger.info("No data to write to the sheet.");
        return;
    }

    const creds = require('../credentials.json');
    // 创建带权限范围的认证实例
    const auth = new GoogleAuth({
        credentials: creds,
        scopes: ['https://www.googleapis.com/auth/spreadsheets'],
    });

    const doc = new GoogleSpreadsheet("sdfadsgsdfgadsfDML-17jbHMdXkgcqWtmvJ0", { auth });

    try {
        await doc.loadInfo();
        const sheet = doc.sheetsByIndex[0];

        await sheet.addRows(data);
        logger.info("Data successfully written to the sheet.");
    } catch (error) {
        logger.error("Failed to write data to the sheet:", error);
    }
}
注意事项
  • 确认credentials.json文件路径正确,且对应的服务账号已获得目标表格的编辑权限
  • v4版本的google-spreadsheetAPI与v3差异较大,若代码中还有其他旧版API调用,需同步替换为v4写法

内容的提问来源于stack exchange,提问作者Carol.Kar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:27:24