获取 TypeError doc.sheetsByTitle 不是函数,google-电子表格

Getting TypeError doc.sheetsByTitle is not a function, google-spreadsheet

我正在使用 'google-spreadsheet' 并成功创建了一个新工作表,但由于某些原因,我无法操作甚至 select 它。我搜索了文档和网站,但仍然找不到解决方案。

async function startup () {
    const doc = new GoogleSpreadsheet(config.sheetID);

    let creds = require('login data')

    await doc.useServiceAccountAuth(creds);

    await doc.loadInfo(); // loads document properties and worksheets
    console.log(doc.title);

    for (var i = 0; i < config.channelID.length; i++) {
        doc.addSheet({ title: config.channelID[i] })

        let sheet = await doc.sheetsByTitle(config.channelID[i])
        
    }
}

(node:50552) UnhandledPromiseRejectionWarning: TypeError: doc.sheetsByTitle is not a function

当我看到“node-google-spreadsheet”的脚本时,似乎doc.sheetsByTitle returns一个对象。 Ref 我认为这可能是您遇到问题的原因。那么下面的修改呢?

发件人:

for (var i = 0; i < config.channelID.length; i++) {
    doc.addSheet({ title: config.channelID[i] })

    let sheet = await doc.sheetsByTitle(config.channelID[i])
    
}

收件人:

for (var i = 0; i < config.channelID.length; i++) {
  await doc.addSheet({ title: config.channelID[i] });
  let sheet = doc.sheetsByTitle[config.channelID[i]];
  console.log(sheet.title);  // You can check the added sheet name here.
}

或者,在您的情况下,doc.addSheet 也 returns sheet 对象。所以你可以使用下面的脚本。

for (var i = 0; i < config.channelID.length; i++) {
  const addedSheet = await doc.addSheet({ title: config.channelID[i] });
  console.log(addedSheet.title);  // You can check the added sheet name here.
}

注:

  • 在此修改后的脚本中,请使用awaitdoc.addSheet
  • 请使用最新版本node-google-spreadsheet。现在,好像是 google-spreadsheet@3.0.13.

参考: