我需要使用谷歌脚本列出子文件夹中的所有文件

时间:2016-05-23 14:55:59

标签: javascript google-apps-script google-spreadsheet-api

我正在尝试为文件夹中的所有文件制作摘要表。这是我到目前为止,但我无法弄清楚如何列出" folderid"的子文件夹中的文件。任何想法都将不胜感激。



//GLOBAL VARIABLES

var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];

function onOpen() {
    ss.getRange(1, 1, 100, 10).clear({contentsOnly: true})

    var id = "folderid";
    var arr = [["CAPITAL PROJECT", "URLs", "OWNER"]];

    var f = DriveApp.getFolderById(id).getFiles()
    while (f.hasNext()) {

        var file = f.next();
        var name = file.getName()
        var url = file.getUrl()
        var own = file.getOwner().getName()

        arr.push([name, url, own]);

        ss.getRange(1,1, arr.length, arr[0].length).setValues(arr);
    }

    ss.getRange(2,1, arr.length, arr[0].length).sort(1)

    var second = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2")
    second.activate()
}




1 个答案:

答案 0 :(得分:1)

获得主文件夹后,您可以获取子文件夹。如果有多个子文件夹,则需要内部循环:

我已经测试了这段代码,但它确实有效:

function getAndListFilesInFolder() {
  var arr,f,file,folderName,subFolders,id,mainFolder,name,own,sh,thisSubFolder,url;

  sh = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  sh.getRange(1, 1, 100, 10).clear({contentsOnly: true})

  id = "Put_Your_FolderID_Here";
  arr = [["CAPITAL PROJECT", "URLs", "OWNER","FOLDER"]];

  mainFolder = DriveApp.getFolderById(id);
  subFolders = mainFolder.getFolders();
  folderName = mainFolder.getName();

  f = mainFolder.getFiles();

  while (f.hasNext()) {
    file = f.next();
    name = file.getName()
    url = file.getUrl()
    own = file.getOwner().getName()

    arr.push([name, url, own, folderName]);
  };

  while (subFolders.hasNext()) {
    thisSubFolder = subFolders.next();
    f = thisSubFolder.getFiles();
    folderName = thisSubFolder.getName();

    while (f.hasNext()) {
      file = f.next();
      name = file.getName()
      url = file.getUrl()
      own = file.getOwner().getName()

      arr.push([name, url, own,folderName]);  
    };
  };

  sh.getRange(1,1, arr.length, arr[0].length).setValues(arr);
  sh.getRange(2,1, arr.length, arr[0].length).sort(1);


  //var second = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2")
  //second.activate()
}