如何通过自定义函数/脚本从具有正确授权的 Google 表格中的文件名中获取文件 URL

我想创建一个自定义函数,从 Google 表格中的文件名中提取驱动器 URL.

I would like to create a custom function that pulls a Drive URL from a file name in Google Sheets.

所以,使用下面的代码:

So, using the code below:

  1. 如果我在单元格 A1
  2. 中有一个有效的文件名
  3. 函数 =getFile(A1) 将返回 URL

  • 当我在脚本编辑器中运行我的脚本时,返回值有效.
  • 当我在工作表中运行函数 getFile() 时,出现以下错误.
  • When I run my script from within the script editor, the return value works.
  • When I run the function getFile() from within my sheet, I get the error below.

我的代码:

function getFile(cell) {

  var filename = encodeURI(cell);

  var url = "https://www.googleapis.com/drive/v3/files?fields=files(id,name)&q=name+contains+'" + filename + "' and trashed=false";
  var params = {
    method: "GET",
    headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true
  };
  var res = UrlFetchApp.fetch(url, params).getContentText();
  var json = JSON.parse(res);
  return res; // outputs response below
  if(json){
    var objFiles = json.files[0];
    var fileID = objFiles.id
    var resURL = "https://docs.google.com/spreadsheets/d/" + fileID;
    Logger.log(resURL);
    //return resURL; // only works when run within script editor
  }

}

错误:

"{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}
"

我猜我的 Auth 令牌有问题.有人可以指导我解决这个问题吗?提前致谢!

I'm guessing something's wrong with my Auth token. Can someone direct me to resolving this? Thanks in advance!

推荐答案

@I'-'I的answer 是正确的.虽然我不确定这是否是您想要的,但这个解决方法怎么样?我也遇到过同样的问题.当时,我使用了以下解决方法.

@I'-'I's answer is correct. Although I'm not sure whether this is what you want, how about this workaround? I have also experienced the same issue. At that time, I had used the following workaround.

  • 使用 PropertiesService 设置和获取访问令牌.

流程如下.

  1. 由时间驱动的触发器每 1 小时设置一次访问令牌.
    • 由此,访问令牌每 1 小时更新一次.因为access token的过期时间是1小时.
  • 这样就可以使用访问令牌了.

修改脚本:

请将此功能安装为时间驱动触发器.当然,你也可以手动运行这个函数.

Modified script:

Please install this function as the time-driven trigger. Of course, you can run manually this function.

function setAccessToken() {
  PropertiesService.getScriptProperties().setProperty("accessToken", ScriptApp.getOAuthToken());
}

在你的脚本中,请修改如下.

In your script, please modify as follows.

var params = {
  method: "GET",
  headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
  muteHttpExceptions: true
};

到:

var params = {
  method: "GET",
  headers: {"Authorization": "Bearer " + PropertiesService.getScriptProperties().getProperty("accessToken")},
  muteHttpExceptions: true
};

注意:

  • 在这种情况下,访问令牌的所有者是项目的所有者.
  • 我认为CacheService也可以使用这个.
    • PropertiesService

相关文章