问题和解决方法:
当使用SpreadsheetApp.openById() 时,使用https://www.googleapis.com/auth/spreadsheets 的范围。看来这是目前的规范。
那么,作为一种解决方法,使用 Sheets API 怎么样?使用Sheets API时,可以使用https://www.googleapis.com/auth/drive.file的范围。
作为重点,https://www.googleapis.com/auth/drive.file范围的官方文档如下。
按文件访问应用程序创建或打开的文件。文件授权是按用户授予的,并在用户取消对应用的授权时撤销。
因此,当您要使用https://www.googleapis.com/auth/drive.file 的范围从电子表格中检索数据时,首先需要由范围创建电子表格。在这个答案中,我想介绍以下流程。
- 将
https://www.googleapis.com/auth/drive.file 的范围设置为 Google Apps 脚本项目。
- 创建一个新的电子表格。
- 从电子表格中检索值。
用法:
1。设置范围。
请创建一个新的 Google Apps 脚本。根据您的问题,我了解到您使用的是独立类型。为此,请将https://www.googleapis.com/auth/drive.file 的范围设置为清单文件。 Ref 请将"oauthScopes": ["https://www.googleapis.com/auth/drive.file"] 添加到appsscript.json 的文件中。这样就可以使用特定的范围了。
2。创建一个新的电子表格。
在使用此脚本之前,please enable Sheets API at Advanced Google services。当您运行以下脚本时,会创建一个新的电子表格,您可以在日志中看到电子表格 ID。请复制身份证。此 ID 将在下一个脚本中使用。这样,https://www.googleapis.com/auth/drive.file 的范围内就会创建一个新的电子表格。
function createNewSpreadsheet() {
const id = Sheets.Spreadsheets.create({properties: {title: "sample"}}).spreadsheetId;
console.log(id)
}
- 当您尝试从不是由该 Google Apps 脚本项目创建的现有电子表格中检索值时,会出现
Requested entity was not found. 错误。因此,在本节中,此 Google Apps 脚本项目将创建一个新的电子表格。
3。从电子表格中获取值。
在使用此脚本之前,请打开创建的电子表格并检查表格名称。并且,作为样本,请将样本值放入单元格中。当您运行以下脚本时,将从电子表格中检索值,您可以在日志中看到它们。
function getValues() {
const spreadsheetId = "###"; // Please set the spreadsheet ID.
const obj = Sheets.Spreadsheets.Values.get(spreadsheetId, "Sheet1");
const values = obj.values;
console.log(values)
}
参考资料: