问题和解决方法:
不幸的是,在现阶段,当使用电子表格服务(SpreadsheetApp)时,需要使用https://www.googleapis.com/auth/spreadsheets的范围。这似乎是当前的规范。比如之前使用DriveApp时,需要使用https://www.googleapis.com/auth/drive的范围。但是,通过谷歌方面的更新,当使用DriveApp.getFiles()时,可以使用https://www.googleapis.com/auth/drive.readonly。所以,我认为电子表格服务的情况可能会在未来的更新中改变。
但是,在当前阶段,需要使用当前规范。因此,需要使用变通方法。在这个答案中,我想提出一个使用范围为 https://www.googleapis.com/auth/spreadsheets.readonly 的电子表格的解决方法。
用法:
1. 准备一个 Google Apps 脚本项目。
请创建一个新的 Google Apps 脚本项目。在这种情况下,您可以同时使用独立类型和容器绑定脚本类型。在这个答案中,我想使用独立类型。如果想直接创建,请访问https://script.new。由此,您可以看到 Google Apps Script 的脚本编辑器。请设置文件名。
2. 启用表格 API。
为了使用https://www.googleapis.com/auth/spreadsheets.readonly 的范围从 Spreadsheet 中检索值,使用了 Sheets API。因此,请在 Advanced Google 服务中启用 Sheets API。 Ref
3.准备清单文件。
在使用脚本之前,请设置清单文件(appsscript.json)。所以,请出示清单文件。 Ref
并且,请按如下方式添加您的预期范围。可以看到enabledAdvancedServices中已经包含了Sheets API。请按以下方式添加"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.readonly"]。
{
"timeZone": "###",
"dependencies": {
"enabledAdvancedServices": [
{
"userSymbol": "Sheets",
"version": "v4",
"serviceId": "sheets"
}
]
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.readonly"]
}
4.准备示例脚本。
请将以下脚本复制并粘贴到您的脚本编辑器中,并设置spreadsheetId,然后保存脚本。
function myFunction() {
const spreadsheetId = "###"; // Please set your Spreadsheet ID.
const res = Sheets.Spreadsheets.get(spreadsheetId);
console.log(res);
}
5. 测试。
当您运行myFunction 时,脚本就会运行。并且,返回电子表格的值。这样,您就可以使用范围为https://www.googleapis.com/auth/spreadsheets.readonly 的 Sheets API 从 Spreadsheet 中检索值。
笔记:
-
https://www.googleapis.com/auth/spreadsheets.readonly 的范围可用于从电子表格中检索值。当您要更新电子表格时,需要使用https://www.googleapis.com/auth/spreadsheets 的范围。请注意这一点。
参考: