【问题标题】:HTTP Post response in Typescript to update google spreadsheetTypescript 中的 HTTP Post 响应以更新谷歌电子表格
【发布时间】:2021-08-23 07:50:15
【问题描述】:

我正在通过以下网址从 google API 更新电子表格:https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append

在更新表单中,我填写了以下属性: 在电子表格 ID 字段中,我输入电子表格的 ID,在范围字段中输入工作表的名称,在 insertDataOption 字段中,我选择 INSERT_ROWS,在 valueInputOption、RAW 和请求正文字段中,以下 object

{
  "values": [
    [
      "id",
      "ser",
      "IP",
      "host",
      "type",
      "auth"
    ],
    [
      "1",
      null,
      null,
      "",
      "Web",
      ""
    ],
    [
      "2",
      null,
      "191.174.230.02",
      "",
      "Proxy",
      ""
    ]
  ]
}

HTTP Post 响应如下:POST https://sheets.googleapis.com/v4/spreadsheets/[spreadsheetId-lex.europa.eu/values/[range-lex.europa.eu:append

我的问题:如何使用我要添加的属性和对象来形成 HTTP Post 响应?也就是说,我如何告诉响应我要在电子表格中添加哪些数据?

【问题讨论】:

  • 我不确定我是否理解,您到底想做什么?只是将该数据添加到电子表格的末尾?打字稿在哪里出现?你想用fetch api 来做吗?或者您只是想知道如何构建请求正文?
  • @iansedano 我想知道如何在 Typescript 代码中通过 API URL (deveolpers.google.com) 做同样的事情。构建具有相同属性和请求正文对象的 HTTP 响应
  • 你从哪里运行 Typescript?浏览器(客户端)?
  • @iansedano 从服务器端使用 Node JS
  • 除了 spreadsheetId 之外,您还必须使用查询参数 range=A1:F&valueInputOption=USER_ENTERED ,它将与您指定的对象主体一起使用

标签: excel google-apps-script google-sheets google-api


【解决方案1】:

如何使用 Node 将数据附加到电子表格

注意:这不使用 Typescript,但由于纯 JavaScript 也是有效的 Typescript,这应该适用于您的 Typescript 项目。

第一步

关注Node.js Quickstart。这将使您的项目设置为:

  • GCP 项目
  • API 激活
  • OAuth 同意屏幕
  • 凭据 - 请务必下载并在项目文件夹中另存为 credentials.json

它还会让您安装 Node.js 库:

npm install googleapis

提出请求

以下是改编自快速入门以使用append 请求的代码:

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// =============
// AUTHORIZATION
// =============

const SCOPES = ['https://www.googleapis.com/auth/spreadsheets'];
const TOKEN_PATH = 'token.json';

fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  authorize(JSON.parse(content), append);
});

function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error while trying to retrieve access token', err);
      oAuth2Client.setCredentials(token);
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

// =============
//    APPEND
// =============

function append(auth){
    const sheets = google.sheets({version: 'v4', auth});
    sheets.spreadsheets.values.append({
        spreadsheetId: '13rdolwpUD4h4RTuExxxxxx', 
        range: 'Sheet1!A1', 
        valueInputOption: 'RAW',
        insertDataOption: 'INSERT_ROWS',  
        resource: {
            "values": [
                [
                  "id",
                  "ser",
                  "IP",
                  "host",
                  "type",
                  "auth"
                ],
                [
                  "1",
                  null,
                  null,
                  "",
                  "Web",
                  ""
                ],
                [
                  "2",
                  null,
                  "191.174.230.02",
                  "",
                  "Proxy",
                  ""
                ]
              ]
        },
    })
}

请务必将电子表格 ID 替换为您的 ID。

当您第一次使用 node . 运行此程序时,系统会提示您转到 URL 以获取 OAuth 流的身份验证代码。一旦你被授权,那么脚本应该执行。

参考

【讨论】:

  • 好的,这就是我想要的,知道如何形成 HTTP 响应。这种格式也适用于使用 batchClear 清除电子表格的内容?
  • 是的,格式类似,但请查看示例文档。此外,IDE 中的自动完成功能也很有帮助
  • 你能帮我解决我的另一个问题吗?关于如何从谷歌 API 获取数据
  • 会类似于上面的sheets.spreadsheets.values.get({...})developers.google.com/sheets/api/reference/rest/v4/…
  • 我是从 API v3 做的,这是唯一一个对我有用的传递参数的方法。但我很难形成它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多