你可以使用googleapis npm包查询Google表格吗?

huangapple go评论88阅读模式
英文:

Can I query a googleSheet using googleapis npm package?

问题

我有一个包含数千行数据的表格,我想要查询它,而不是每次都获取所有数据。

我查看了查询语言,但似乎不适用于我的情况。

我正在使用服务帐户进行身份验证:

const auth = new google.auth.GoogleAuth({
  credentials: googleCredentials,
  scopes: "https://www.googleapis.com/auth/spreadsheets",
});

并且使用batchGet来一次获取多个标签页的数据。

const standardSpreadsheetData = await sheets.spreadsheets.values.batchGet({
  auth,
  spreadsheetId: regularSpreadsheetId,
  ranges: regularRanges,
});

但我似乎无法弄清楚在哪里添加查询。

我想要查询的内容类似于这样:

select * where B = '9831'

有关查找的想法在哪里呢?

英文:

I have a sheet that has thousands of rows and I am trying to query it instead of fetching everything every time.
I took a look at the Query language, but it doesn't seem to fit my case.

I'm using a Service account to authenticate:

const auth = new google.auth.GoogleAuth({
credentials: googleCredentials,
scopes: "https://www.googleapis.com/auth/spreadsheets",
});

and using the batchGet to get multiple tabs at once.

const standardSpreadsheetData = await sheets.spreadsheets.values.batchGet({
auth,
spreadsheetId: regularSpreadsheetId,
ranges: regularRanges,
});

But I can't seem to figure where I would be able to add the query.

What I am trying to query is something like this:

select * where B = ''9831"

Any ideas on where to look?

答案1

得分: 2

I believe your goal is as follows.

  • 您希望通过查询,例如select * where B = '''9831"'来检索行值。
  • 您希望使用Googleapis的服务帐户来实现这一目标,用于Node.js。

修改点:

  • 我猜测您的查询select * where B = '''9831"'可能是select * where B = ''9831''

  • 不幸的是,在当前阶段,类似select * where B = ''9831''的查询无法与Sheets API一起使用。在这种情况下,需要使用访问令牌来使用查询语言的终点。参考

当这些修改点反映在示例脚本中时,以下示例脚本如何?

示例脚本:

const { google } = require("googleapis");
const request = require("request");

// 请在此处使用您的脚本。
const auth = new google.auth.GoogleAuth({
  credentials: googleCredentials,
  scopes: "https://www.googleapis.com/auth/spreadsheets",
});

const spreadsheetId = "###"; // 请设置电子表格ID。
const sheetId = "###"; // 请设置搜索文本。在您的情况下,它是ID。
const query = "select * where B='9831'"; // 这是搜索的查询。

auth
  .getAccessToken()
  .then((accessToken) => {
    const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:csv&gid=${sheetId}&tq=${encodeURIComponent(query)}`;
    request(
      {
        url,
        method: "GET",
        headers: { authorization: `Bearer ${accessToken}` },
      },
      (err, res, result) => {
        if (err) {
          console.log(err);
          return;
        }
        if (result != "") {
          const [, ...res] = result.split("\n").map((e) =>
            e.split(",").map((f) => {
              const t = f.replace(/"/g, "");
              return isNaN(t) ? t : Number(t);
            })
          );
          console.log(res);
        }
      }
    );
  })
  .catch((err) => console.log(err));
  • 访问令牌是从服务帐户中检索的。然后,该访问令牌用于请求。运行此脚本时,将显示包括搜索行值的数组。

注意:

  • 在此脚本中,结果值导出为CSV数据。然后,使用简单的脚本解析它。
  • 此脚本是一个简单的示例脚本。因此,如果解析CSV数据不正确,请使用Node.js的CSV数据解析器。

参考资料

英文:

I believe your goal is as follows.

  • You want to retrieve the row values by the query like select * where B = ''9831".
  • You want to achieve this using the service account with googleapis for Node.js.

Modification points:

  • I guessed that your query of select * where B = ''9831" might be select * where B = '9831'.

  • Unfortunately, in the current stage, the query like select * where B = '9831' cannot be used with Sheets API. In this case, it is required to use the endpoint for the query language using the access token. Ref

When these points are reflected in a sample script, how about the following sample script?

Sample script:

const { google } = require("googleapis");
const request = require("request");

// Please use your script here.
const auth = new google.auth.GoogleAuth({
  credentials: googleCredentials,
  scopes: "https://www.googleapis.com/auth/spreadsheets",
});

const spreadsheetId = "###"; // Please set the Spreadsheet ID.
const sheetId = "###"; // Please set the search text. In your case, it's ID.
const query = "select * where B='9831'"; // This is the query for searching.

auth
  .getAccessToken()
  .then((accessToken) => {
    const url = `https://docs.google.com/spreadsheets/d/${spreadsheetId}/gviz/tq?tqx=out:csv&gid=${sheetId}&tq=${encodeURIComponent(query)}`;
    request(
      {
        url,
        method: "GET",
        headers: { authorization: `Bearer ${accessToken}` },
      },
      (err, res, result) => {
        if (err) {
          console.log(err);
          return;
        }
        if (result != "") {
          const [, ...res] = result.split("\n").map((e) =>
            e.split(",").map((f) => {
              const t = f.replace(/"/g, "");
              return isNaN(t) ? t : Number(t);
            })
          );
          console.log(res);
        }
      }
    );
  })
  .catch((err) => console.log(err));
  • The access token is retrieved from the service account. And, the access token is used for the request. When this script is run, an array including the searched row values is shown.

Note:

  • In this script, the result value is exported as CSV data. And it is parsed with a simple script.
  • This script is a simple sample script. So, if parsing the CSV data is not correct, please use the parser of CSV data for Node. js.

Reference

huangapple
  • 本文由 发表于 2023年5月30日 09:24:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76361086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定