我相信您的目标如下。
FileName
用作Google Spreadsheet的自定义功能。
不幸的是,当使用自定义函数时,在当前规范中,除需要授权的几种方法(例如,其中一种是UrlFetchApp。)外,大多数方法无法使用。这样,DriveApp.getFileById(id)
您的脚本中不能与自定义功能一起使用。但是有一种解决方法。在自定义功能上,可以使用UrlFetchApp。在这个答案中,我想建议使用带有UrlFetchApp的Web应用作为授权包装。这样,可以使用Web Apps完成授权。因此,您的函数可以通过自定义函数运行。
请复制以下脚本并将其粘贴到脚本编辑器中并保存。
const key = "samplekey"; // This is a key for using Web Apps. You can freely modify this.
// This is your function.
function FileName_(id) {
var ss = DriveApp.getFileById(id);
return ss.getName();
}
// Web Apps using as the wrapper for authorizing.
function doGet(e) {
let res = "";
if (e.parameter.key === key) {
try {
res = FileName_(e.parameter.id);
} catch (err) {
res = `Error: ${err.message}`;
}
} else {
res = "Key error.";
}
return ContentService.createTextOutput(JSON.stringify({value: res}));
}
function Filename(id) {
const webAppsUrl = "https://script.google.com/macros/s/###/exec"; // Please set the URL of Web Apps after you set the Web Apps.
const res = UrlFetchApp.fetch(`${webAppsUrl}?id=${id}&key=${key}`);
if (res.getResponseCode() != 200) throw new Error(res.getContentText());
return JSON.parse(res.getContentText()).value;
}
https://script.google.com/macros/s/###/exec
。
https://script.google.com/macros/s/###/exec
为上述脚本的url。并请重新部署Web Apps。这样,最新的脚本就会反映到Web应用程序中。所以请注意这一点。当文件ID放在单元格“ A1”中时,请=filename(A1)
作为自定义功能放在单元格中。这样,脚本将运行并返回响应值。
上面的示例脚本是用于测试脚本的简单示例脚本。因此,当您想使用各种方法时,这篇文章可能会有用。
请在启用V8时使用此脚本。
作为其他方法,我认为将文件ID手动放入“ B”列时,可以使用可安装的OnEdit触发器。示例脚本如下。请设置工作表名称。并且请将触发器安装到的功能installedOnEdit
。Ref这样,当文件ID放在的列“ B”时sheetName
,文件ID放在“ C”列。
function installedOnEdit(e) {
const sheetName = "Sheet1";
const range = e.range;
const sheet = range.getSheet();
if (!(sheet.getSheetName() == sheetName && range.getColumn() == 2 && range.getRow() > 1)) return;
const value = range.getValue();
let res = "";
try {
res = DriveApp.getFileById(value).getName();
} catch(e) {
res = e.message;
}
range.offset(0, 1).setValue(res);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句