首页 > 解决方案 > 如何在 nodejs 中使用谷歌电子表格

问题描述

我想使用 google-spreadsheet API 来获取数据并将数据写入我的 Discord 机器人中的工作表(使用 discord.js)。出于某种原因,我无法让它工作。这是我的代码:

const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')

module.exports = {
    /...
    execute(message, args) {
        accessSpreadsheet()
    }
}

async function accessSpreadsheet() {
    const doc = new GoogleSpreadsheet('<id was here>')
    doc.useServiceAccountAuth(creds)
        .then(() => {
            doc.getInfo()
                .then(info => {
                    console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
                    const sheet = info.worksheets[0]
                    console.log(
                        `sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
                    )
                })
        })
}

这是我不断收到的错误:

 (node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
     at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
     at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
     at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
     at IncomingMessage.emit (events.js:327:22)
     at endReadableNT (_stream_readable.js:1221:12)
     at processTicksAndRejections (internal/process/task_queues.js:84:21)
 (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
 (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

标签: node.jsdiscord.jsgoogle-sheets-api

解决方案


我实际上应该使用 async/await 来实现这一点。我的代码变成了:

async function accessSpreadsheet(message, args, msg) {
    const doc = new GoogleSpreadsheet('<id was here>')
    await doc.useServiceAccountAuth(creds)

    await doc.loadInfo()
    console.log(doc.title) //whatever you want to log goes here
})

推荐阅读