1
votes

I am making a tab in a Google Sheet to keep track of files in a particular folder. I have successfully modified a script I found online to get the list by folder id, but I can't seem to figure out how to get the results to appear in order by name. Here is the code I'm using but I'm putting the folder id in place of myFolderId:

 /**
 * List all files in Google Drive folder.
 *
 * @param {string} folderName    (optional) Name of folder on Google Drive
 *
 * Adapted from:
 * http://ctrlq.org/code/19854-list-files-in-google-drive-folder
 * https://gist.github.com/hubgit/3755293
 */
function listFilesInFolder(id) {
  // If we have not been provided a folderName, assume we will interact with     user.
  var interactive = (typeof folderName === 'undefined');

  // Get name of folder to list
  if (interactive) {
    id = 'myFolderId';
  }

  if (id === '')
    return;  // No name provided, exit quietly

  var folder = DriveApp.getFolderById(id);
  var contents = folder.getFiles();

  var file, data, sheet = SpreadsheetApp.getActiveSheet();
  sheet.clear();

  sheet.appendRow(["Name", "Date"]);

  // Loop over files in folder, using file iterator
  while (contents.hasNext()) {
    file = contents.next();

    if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
      // Skip displaying spreadsheets - I don't know why...
      continue;
    }

    data = [ 
      file.getName(),
      file.getDateCreated(),
    ];

    sheet.appendRow(data);
  }
}
2

2 Answers

3
votes

First option, sort the sheet

enter image description here

Second option, I tried to comment the script so you will understand the steps

/*
 * Logs in a SpreadSheet the files of a given folder
  * @param {string} folder id
 */

function listFilesInFolder(id){
  // You can change it and get ss from a given ID
  var sheet = SpreadsheetApp.getActiveSheet();

  // array to hold our data
  var data = [];

  // An iterator that allows scripts to iterate over a potentially large collection of files
  var files = DriveApp.getFolderById(id).getFiles();

  // We loop on iterator and append results to an array
  while (files.hasNext()) {
   var file = files.next();
   // we append our data with result, we have now an array of files
   data.push(file);
  }

  // lets sort our array
  data = data.sort(function(file1, file2){
      if (file1.getName().toLowerCase() < file2.getName().toLowerCase())
          return -1;
      else if (file1.getName().toLowerCase() > file2.getName().toLowerCase())
          return 1;
      else 
        return 0;
    }
  )

  // lets add it to our sheet
  // some labels
  sheet.appendRow(["Name", "Date"]);
  // real data
  data.forEach(function(file){
    sheet.appendRow([file.getName(), file.getDateCreated()])
  })
}

gist link

0
votes

add this line at the end

//for sorting the Name column    
sheet.sort(1);