当您在电子表格中手动输入导入范围函数时,您会收到一个弹出窗口,必须“允许访问”。
但是,我正在尝试通过脚本找到一种方法来执行此操作,因为我正在创建许多电子表格,每个电子表格都具有查询导入范围功能(我“拥有”具有要导入数据的电子表格)。有太多我无法通过弹出窗口手动“允许访问”并更新功能以包含查询功能。
因此,我正在寻找应用程序脚本中的函数调用,它可以执行与弹出窗口相同的操作。下面的代码段示例。
有人知道可以“允许访问”的功能吗? 斯特凡
// create new spreadsheet file
...
var ss = createSpreadsheet(fileName);
var spreadsheet = SpreadsheetApp.open(ss);
var sheet = spreadsheet.getSheetByName("Sheet1");
// Add student as Viewer
spreadsheet.addViewer(studentEmail);
// Add ImportRange function
var sheet = spreadsheet.getSheets()[0];
var cell = sheet.getRange("A1");
var filter = "select * where Col3='" + studentEmail + "'";
var qry = '=QUERY(importRange("' + fileKey + '","14-15S2!A1:AE");"' + filter + '";1)';
cell.setValue(qry);
// I need a function to 'allow access' here, so the function can be allowed access. Otherwise, it throws an error.
...
最佳答案
@Franzi suggested using undocumented approach which works并且不需要公开捐助者/来源电子表格。以下是您可以通过 Google App Script 执行此操作的方法:
function addImportrangePermission() {
// id of the spreadsheet to add permission to import
const ssId = SpreadsheetApp.getActiveSpreadsheet().getId();
// donor or source spreadsheet id, you should get it somewhere
const donorId = '1GrELZHlEKu_QbBVqv...';
// adding permission by fetching this url
const url = `https://docs.google.com/spreadsheets/d/${ssId}/externaldata/addimportrangepermissions?donorDocId=${donorId}`;
const token = ScriptApp.getOAuthToken();
const params = {
method: 'post',
headers: {
Authorization: 'Bearer ' + token,
},
muteHttpExceptions: true
};
UrlFetchApp.fetch(url, params);
}
通常不需要,但在极少数情况下,您可能希望在 appscript.json
list 中添加所需的 oauthScopes:
...,
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/script.external_request"
],
...
关于javascript - 如何允许通过应用程序脚本访问 importrange 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28038768/