https://docs.google.com/spreadsheets/d/1sQyBTh7xCptnvr2SOQyEovmgIi6U-UapvDQOphk2Qxg/edit?usp=sharing
以上是我的Google表格文件,该文件链接到上传收据图片文件的表单,并为上传的收据编目。
我对App Scripts作业有两个要求:
1) Get a short URL for the uploaded file.
STATUS: ACHIEVED!!!
2) Fetch the name of the uploaded file for reference.
STATUS: NOT ACHIEVED, GET ERROR CODE BELOW WHEN CLICKING MENU ITEM
TO RUN THE SCRIPT.
错误:“找不到具有给定ID的项目,或者您无权访问该项目。”
我将在稍后粘贴我的App Scripts代码。
这是我到目前为止所做的:
1) Enabled both the Drive API & URL Shortener APIs in the script
2) Enabled both APIs on Google API Console for this project
3) Saved my code in Apps Script
4) Ran onOpen() function to establish the Custom Menu in my spreadsheet
(it adds the menu when I refresh the spreadsheet).
5) I am the owner of all of the following:
+the Drive account ALL of the pertinent files are stored on,
+the App Script that was created,
+the project in the Google API console.
6) I have given consent to access the process when the Script first runs
with the same Google Account.
以下是代码:
function onOpen() {
SpreadsheetApp.getUi()
.createMenu("URL Manager")
.addItem("Shorten","short")
.addItem("Get File Names","names")
.addToUi();
}
function short() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
var output1 = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var url = UrlShortener.Url.insert({longUrl: data[i][0]});
output1.push([url.id]);
}
//puts the short url one column to the right
range.offset(0,1).setValues(output1);
}
function names() {
var range = SpreadsheetApp.getActiveRange(), data = range.getValues();
//var data must be converted to string since it is the long url of the
//file, then parsed for index of "=" (var n), then I sliced out the fileID
//with var m
var str = data.toString();
var n = str.indexOf("=");
var m = str.slice(n+1)
var output2 = [];
for(var i = 0, iLen = data.length; i < iLen; i++) {
var file = DriveApp.getFileById({fileID: m[i][0]});
output2.push([file.getName()]);
}
//puts the file name 1 column to the left
range.offset(0,-1).setValues(output2);
}
所以我重新加载我的电子表格,单击以激活我想要获取短网址和文件名的单元格,然后单击菜单项以执行脚本功能。 short()有效,names()没有。请参阅上面的错误。
这是我的问题:
如何删除文件访问的隐藏限制?
我找到了此代码的前2/3(onOpen&amp; short函数)以及一个很好的解释here。谢谢,亚历克斯!
答案 0 :(得分:0)
试试这个:
function names() {
var range = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var rng=range.getDataRange()
var data = rng.getValues();
var output2 = [];
for(var i = 1, iLen = data.length; i < iLen; i++) {
var str = data[i][2].toString();
var n = str.indexOf("=");
var m = str.slice(n+1)
var file = DriveApp.getFileById(m);
output2.push([file.getName()]);
}
for(var j=0;j<output2.length;j++){
range.getRange(j+2,2).setValue(output2[j][0]);
}}
答案 1 :(得分:0)
Ed Nelson,你是完全正确的!
有问题的代码行是:
var file = DriveApp.getFileById({fileID: m[i][0]});
这篇文章
{fileID: m[i][0]}
在括号内返回[fileID],而DriveApp.getFileByID()实用程序需要一个字符串输入(当包含'[]'时无法读取。)
这是工作解决方案:
for (var i=0; i < data.length; i++) {
var fileID = data[i][0].toString();
var file = DriveApp.getFileById(fileID);
TADA !!!
谢谢,Ed!