Home > Back-end >  Sort files Google Apps Script
Sort files Google Apps Script

Time:06-26

I have this code in Apps Script, it gets all files of a folder (expofd) and print the ID's in the Google Sheet. But each time the code get the files in a different order and I need any kind of sort (Alphabetically by name, not by id) or whatever, but the printing in the Sheet have to be always in the same order. Also, It would be nice a code modification to filter the folder files and get only which have certain sufix.

  var list = [];
  list.push(['ID']);
  var files = expofd.getFiles();
  while (files.hasNext()){
  file = files.next();
  var row = []
  row.push(file.getId())
  list.push(row)
  ;
  
  }
  
  sh.getRange(2,2,list.length,list[0].length).setValues(list);

Thanks!

CodePudding user response:

Try this

function myFunction() {
  var expofd = DriveApp.getFolderById('#############') // your folder id
  var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  var sufix = '.pdf' // adapt as necessary
  var list = [];
  var files = expofd.getFiles();
  while (files.hasNext()) {
    file = files.next();
    list.push([file.getName(),file.getId()])
  }
  var result = [['name','id'], ...list.filter(r => r[0].includes(sufix)).sort()]
  sh.getRange(1,1, result.length, result[0].length).setValues(result);
}

You will get the list sorted by name and filtered by sufix

CodePudding user response:

Just in case here is the more fancy (and probably more quick) way to search files with Drive API:

function myFunction() {
  var mask = '.jpg';
  var folder_id = '###'; // put your folder ID instead of ###
  var query = `title contains "${mask}" and trashed = false and "${folder_id}" in parents`;
  
  var findings = Drive.Files.list({ q: query }) || [];
  var table = [['name', 'id'], ...findings.items.map(f => [f.title, f.id]).sort()];
  
  SpreadsheetApp.getActiveSheet().clear().getRange(1,1,table.length,2).setValues(table);
}

Make sure you add the Drive API in Script Editor:

enter image description here

Reference:

  • Related