問題描述
我想創(chuàng)建一個(gè)自定義函數(shù),從 Google 表格中的文件名中提取驅(qū)動(dòng)器 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:
- 如果我在單元格
A1
中有一個(gè)有效的文件名 函數(shù)
=getFile(A1)
將返回 URL
- 當(dāng)我在腳本編輯器中運(yùn)行我的腳本時(shí),返回值有效.
- 當(dāng)我在工作表中運(yùn)行函數(shù)
getFile()
時(shí),出現(xiàn)以下錯(cuò)誤.
- 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
}
}
錯(cuò)誤:
"{
"error": {
"errors": [
{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Invalid Credentials"
}
}
"
我猜我的 Auth 令牌有問題.有人可以指導(dǎo)我解決這個(gè)問題嗎?提前致謝!
I'm guessing something's wrong with my Auth token. Can someone direct me to resolving this? Thanks in advance!
推薦答案
@I'-'I的answer 是正確的.雖然我不確定這是否是您想要的,但這個(gè)解決方法怎么樣?我也遇到過同樣的問題.當(dāng)時(shí),我使用了以下解決方法.
@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 設(shè)置和獲取訪問令牌.
流程如下.
- 由時(shí)間驅(qū)動(dòng)的觸發(fā)器每 1 小時(shí)設(shè)置一次訪問令牌.
- 由此,訪問令牌每 1 小時(shí)更新一次.因?yàn)閍ccess token的過期時(shí)間是1小時(shí).
- 這樣就可以使用訪問令牌了.
修改腳本:
請(qǐng)將此功能安裝為時(shí)間驅(qū)動(dòng)觸發(fā)器.當(dāng)然,你也可以手動(dòng)運(yùn)行這個(gè)函數(shù).
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());
}
在你的腳本中,請(qǐng)修改如下.
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
};
注意:
- 在這種情況下,訪問令牌的所有者是項(xiàng)目的所有者.
- 我認(rèn)為CacheService也可以使用這個(gè).
- PropertiesService
這篇關(guān)于如何通過自定義函數(shù)/腳本從具有正確授權(quán)的 Google 表格中的文件名中獲取文件 URL的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!