Retirving All files in Folder with Spreadsheet

This sample retrieves all files in a folder with spreadsheet. When there are some folders in the folder with spreadsheet, this script can retrieve all files in all folders. This script has to be a container-bound script for spreadsheet.

Script :

function getFileList(){
  var folderlist = (function(folder, folderSt, results){
    var ar = [];
    var folders = folder.getFolders();
    while(folders.hasNext()) ar.push(folders.next());
    folderSt += folder.getId() + "#_aabbccddee_#";
    var array_folderSt = folderSt.split("#_aabbccddee_#");
    array_folderSt.pop()
    results.push(array_folderSt);
    ar.length == 0 && (folderSt = "");
    for (var i in ar) arguments.callee(ar[i], folderSt, results);
    return results;
  })(DriveApp.getFolderById(
    DriveApp.getFileById(
      SpreadsheetApp.getActiveSpreadsheet().getId()
    ).getParents().next().getId()
  ),"",[]);

  var filelist = [];
  for (var i in folderlist){
    var folderid = folderlist[i][folderlist[i].length - 1];
    var temp = [];
    var folder = DriveApp.getFolderById(folderid);
    var files = folder.getFiles();
    var foldername = folder.getName();
    while(files.hasNext()){
      var file = files.next();
      temp.push([foldername, file.getName()]);
    }
    filelist.push(temp);
  }
  return Array.prototype.concat.apply([], filelist);
}

function main() {
  var data = getFileList();
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  ss.getRange(1,1,data.length,data[0].length).setValues(data);
}

Result :

 Share!