Apps 脚本 - 使用 Google Sheets REST API v4 - 未写入值 - 无错误消息

Apps Script - Using Google Sheets REST API v4 - Values not being written - No error message

一切正常,但没有将值写入电子表格。我什至从 POST 请求中得到部分有效的响应。我只是不知道把 values 放在哪里我试过把它们放到有效载荷中,在 URL

function writeToSheet() {
  var id,options,range,response,sh,ss,url,values;

  id = 'Put the spreadsheet ID here';
  range = "Sheet1!A1:A1";
  values = "['3','two','nine']";

  url = "https://sheets.googleapis.com/v4/spreadsheets/" +
    id + "/values/" + range + ":append?valueInputOption=USER_ENTERED";

  options = {
    "method":"post",
    "muteHttpExceptions": true,
    "headers": {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    }
  }

  response = UrlFetchApp.fetch(url,options)
  response = JSON.parse(response);

  Logger.log('response ' + JSON.stringify(response))
}

我试过:

url = "https://sheets.googleapis.com/v4/spreadsheets/" + id + 
  "/" + values + "/" + range + ":append?valueInputOption=USER_ENTERED";

我试过将 values 属性 放入负载中。没有任何效果。

我的示波器工作正常。我没有收到任何授权错误。这是我的清单文件,其中包含运行良好的范围。

{
  "timeZone": "America/New_York",
  "dependencies": {
  },
  "webapp": {
    "access": "MYSELF",
    "executeAs": "USER_DEPLOYING"
  },
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://www.googleapis.com/auth/drive",
                  "https://www.googleapis.com/auth/script.external_request"]
}

我什至从 POST 请求中得到了看起来合法的响应,除了值。

  /*  The response I'm getting back

  {
    "spreadsheetId":"ID Here",
    "tableRange":"Sheet1!A1:C2",
    "updates":{
      "spreadsheetId":"ID here",
      "updatedRange":"Sheet1!A3"
      }
  }

  */

我将要写入电子表格的值放在哪里?

这个修改怎么样?

修改点:

  • 需要在 header 中包含 "application/json"
  • 请求 body 是 {values: [['3','two','nine']]}
    • 假设您要将 '3','two','nine' 的值分别附加到 A、B 和 C 列。
    • 如果要将 '3','two','nine' 的值分别附加到第 1、2 和 3 行,请使用 {values: [['3'],['two'],['nine']]}

修改脚本:

function writeToSheet() {
  var id,options,range,response,sh,ss,url,values;

  id = 'Put the spreadsheet ID here';
  range = "Sheet1!A1:A1";
  values = {values: [['3','two','nine']]}; // Modified

  url = "https://sheets.googleapis.com/v4/spreadsheets/" +
    id + "/values/" + range + ":append?valueInputOption=USER_ENTERED";

  options = {
    "method":"post",
    "muteHttpExceptions": true,
    "headers": {
      "Authorization": "Bearer " + ScriptApp.getOAuthToken()
    },
    "contentType": "application/json", // Added
    "payload": JSON.stringify(values) // Added
  }

  response = UrlFetchApp.fetch(url,options)
  response = JSON.parse(response);

  Logger.log('response ' + JSON.stringify(response))
}

参考资料:

如果这不起作用,我可以向您询问错误消息吗?我想修改一下。