首页 > 解决方案 > Googlespreedsheet 查询在节点 js 中不起作用

问题描述

我目前正在使用 google spreedsheet api v4。我希望使用查询参数仅选择单元格中具有特定 ID 的行。例如,在我希望选择与传递的参数匹配的行并且不会带来其余数据。就像 php select * from db where id = "" ;(让我把它简单点,以便人们理解,看我想做的就像我们使用选择查询一样我只想选择 SheetID 值为的行等于我传递的参数。我不希望像我们通常使用其他数据库(如 mysql 等)那样返回整个 json 数组只是一条记录)但我的代码不起作用。这是我的代码

(async () => {
    await doc.useServiceAccountAuth(creds);
        await doc.loadInfo();
        const sheet = doc.sheetsByIndex[1];
        const rows = await sheet.getRows({
            query:'Clan = clan-12'
        });
        // rows = rows.map(a => a._rawData)
        rows.forEach(row =>{
             printStudent(row);
         });
      
     
    })()

function printStudent(data){
    console.log(data.Clan);
    console.log(data.SheetId);
    console.log(data.Enabled);
}

我已经搜索了整个文档,但无法了解它为什么不起作用?googlespreed sheet api 版本是 4.0,google spreedsheet 的 node js 库是最新的 3.1.15。任何的意见都将会有帮助。

标签: javascriptnode.jsgoogle-sheetsgoogle-sheets-api

解决方案


我相信你的目标和现状如下。

  • 您想通过使用类似的查询搜索值来检索行select * from db where id = ""
  • 您正在使用“谷歌电子表格”库。参考
  • 您已经能够使用带有“google-spreadsheet”的 Sheets API 来获取和放置值。

修改点:

  • 在当前阶段,搜索查询不能直接与 Sheets API 一起使用。因此,在这种情况下,需要使用解决方法。在这个答案中,我想提出解决方法。
  • 在此解决方法中,电子表格的查询语言与“google-spreadsheet”一起使用。因此,访问令牌是从“google-spreadsheet”的授权脚本中检索的。

当以上几点反映到您的脚本时,它变成如下。

修改后的脚本:

在使用此脚本之前,请设置变量。在此示例脚本中,从 Google 电子表格中第二个选项卡的“A”列中搜索 ID。如果要从其他列搜索ID,请修改query

const { GoogleSpreadsheet } = require("google-spreadsheet");
const request = require("request");
// const csvParse = require("csv-parse"); // If you want to retrieve the values an array, please use this.

const creds = require("../credentialfile.json");  // Please set your credential file of the service account.

async function main() {
  const id = "sampleId"; // Please set the search text. In your case, it's ID.
  const query = `select * where A='${id}'`; // This is the query for searching.
  const spreadsheetId = "###"; // Please set the Spreadsheet ID.

  const doc = new GoogleSpreadsheet(spreadsheetId);
  await doc.useServiceAccountAuth(creds);
  await doc.loadInfo();
  const sheet = doc.sheetsByIndex[1]; // It seems that in your script, the ID is searched from the 2nd tab in Spreadsheet.
  const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:csv&gid=${sheet.sheetId}&tq=${encodeURI(query)}`;
  request(
    {
      url: url,
      method: "GET",
      headers: {authorization: `Bearer ${doc.jwtClient.credentials.access_token}`},
    },
    (err, res, result) => {
      if (err) {
        console.log(err);
        return;
      }
      console.log(result);
      // if (result != "") csvParse(result, {}, (err, ar) => console.log(ar));  // If you want to retrieve the values an array, please use this.
    }
  );
}

main();

参考:


推荐阅读