所需权限:https://www.googleapis.com/auth/spreadsheets

abu*_*nte 2 google-sheets google-apps-script

我在 appscript 上创建了一个简单的代码,用于从 URL 中获取 Google Drive 文件名

function FileName (URL) {
  var ss = SpreadsheetApp.openByUrl(URL);
  return ss.getName();
}
Run Code Online (Sandbox Code Playgroud)

当我运行时出现错误:

例外:您无权调用 SpreadsheetApp.openByUrl。所需权限: https: //www.googleapis.com/auth/spreadsheets (linha 6)。

我已经在高级 Google 服务区域启用了 Drive 和 Sheets API,因此“https://www.googleapis.com/auth/spreadsheets”应该没问题,但事实并非如此。

我怎样才能做到这一点?

我在此链接中创建了一个示例表,其中包含问题复制。

soM*_*rio 5

Explanation of the issue:

You are using a custom function.

It is very well explained in the official documentation:

If your custom function throws the error message You do not have permission to call X service., the service requires user authorization and thus cannot be used in a custom function.

As the message clearly states, you are not allowed to use services that require authorization such as SpreadsheetApp.openByUrl(URL) within a custom function.

There is also a table that particularly points out that SpreadsheetApp.openByUrl(URL); can not be used within a custom function:

在此输入图像描述

Workarounds:

You can use regular functions in multiple ways:

  1. Implemented as custom menu buttons,
  2. Execute them from the script editor,
  3. Execute them via simple triggers,
  4. Create an addon menu etc.

Regular function version of your script:

function FileName () {
  var URL = "spreadsheet_url"
  var ss = SpreadsheetApp.openByUrl(URL);
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  sheet.getRange('A1').setValue(ss.getName());
}
Run Code Online (Sandbox Code Playgroud)

Upon execution (see screenshot), this script will set the value of cell A1 of Sheet1 to the name of the spreadsheet file.

在此输入图像描述

I would advice you to look for the functions I used in this script in the official documentation to see what each of them does.

Update:

我刚刚打开您的工作表,看到您正在使用SpreadsheetApp.openByUrl(URL);,但此方法仅适用于电子表格,因此是类名称SpreadsheetApp。如果你想打开文件 ID,那么你需要使用getFileById(id)。我在第一列中看到您有文件 URL,但没有方法通过 URL 打开文件。来自这样的文件的 id:

https://drive.google.com/file/d/1d-2L5kGZWbUa_p7iLgBBa59QqZiyIhgp/view?usp=sharing

是:

1d-2L5kGZWbUa_p7iLgBBa59QqZiyIhgp

因此你需要使用

var files = DriveApp.getFileById('1d-2L5kGZWbUa_p7iLgBBa59QqZiyIhgp')

代码片段将是这样的:

function FileName () {
  var URL = "1d-2L5kGZWbUa_p7iLgBBa59QqZiyIhgp"
  var file = DriveApp.getFileById(URL);
  var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  sheet.getRange('B1').setValue(file.getName());
}
Run Code Online (Sandbox Code Playgroud)

请熟悉一下 GAS,因为这个问题刚刚成为一个需要更多关注的问题。