我正在从Google驱动器的文件夹中获取文件,然后尝试在电子表格中插入指向它们的链接。问题是使用 var ezIter = folderez.getFiles();似乎随机返回。 我希望它们按字母顺序排列。这可能吗?
这是我当前的代码。它工作正常,但链接到文件的顺序混乱,这使所有事情搞砸了。
function getFiles() {
var dApp = DriveApp;
var vfolder = dApp.getFoldersByName("video").next();
var yearfolder = vfolder.getFoldersByName("2018").next();
var gamefolder = yearfolder.getFoldersByName("game1").next();
var folderez = gamefolder.getFoldersByName("ez").next();
var ezIter = folderez.getFiles();
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(yearfolder+gamefolder);
var i = 2;
while (ezIter.hasNext()) {
var file = ezIter.next();
var name = file.getName();
var url = file.getUrl();
range = 'AC'+(i);
var filename = 'ezvideo'+(i-1);
var semi = ";";
var hyp = "=hyperlink(\"";
var quot = "\"";
var clos = ")";
var title = hyp + url + quot + semi + quot + filename + quot + clos; // str='=hyperlink("' + f.getUrl() + '","' + f.getName() + '")';
ss.getRange(range).setValue(title);
i++;
}
答案 0 :(得分:0)
我不知道此API的工作原理,但这可以帮助您对文件进行排序。
首先,完全删除while
循环,然后粘贴以下内容:
var files = [];
// creates an array of file objects
while (ezIter.hasNext()) {
files.push(ezIter.next());
}
// sorts the files array by file names alphabetically
files = files.sort(function(a, b){
var aName = a.getName().toUpperCase();
var bName = b.getName().toUpperCase();
return aName.localeCompare(bName);
});
files.forEach(function(file){
var name = file.getName();
var url = file.getUrl();
range = 'AC'+(i);
var filename = 'ezvideo'+(i-1);
var semi = ";";
var hyp = "=hyperlink(\"";
var quot = "\"";
var clos = ")";
var title = hyp + url + quot + semi + quot + filename + quot + clos; // str='=hyperlink("' + f.getUrl() + '","' + f.getName() + '")';
ss.getRange(range).setValue(title);
i++;
});
更新:根据tehhowch的优化建议,您可以为每个文件调用getName
,如下所示:
var files = [];
// creates an array of file objects
while (ezIter.hasNext()) {
var file = ezIter.next();
files.push({name: file.getName(), url: file.getUrl()});
}
// sorts the files array by file names alphabetically
files = files.sort(function(a, b){
var aName = a.name.toUpperCase();
var bName = b.name.toUpperCase();
return aName.localeCompare(bName);
});
files.forEach(function(file){
var name = file.name;
var url = file.url;
range = 'AC'+(i);
var filename = 'ezvideo'+(i-1);
var semi = ";";
var hyp = "=hyperlink(\"";
var quot = "\"";
var clos = ")";
var title = hyp + url + quot + semi + quot + filename + quot + clos; // str='=hyperlink("' + f.getUrl() + '","' + f.getName() + '")';
ss.getRange(range).setValue(title);
i++;
});