Search code examples
google-apps-scriptgoogle-sheetsoptimizationgoogle-drive-api

Is there a faster way to create google spreadsheet in specific folder?


Hello, friends! To create a new spreadsheet in specific folder I use following script

function create_ss_in_folder(folder, name) {
  var ss = SpreadsheetApp.create(name);
  var id = ss.getId();
  var file = DriveApp.getFileById(id);
  var new_file = file.makeCopy(name, get_folder_by_name(folder));
  id = new_file.getId();
  DriveApp.removeFile(file);
  return id;
}

It take over 8.4 second to run, mainly due to makeCopy call (6.672 sec). So, if there a faster way to create google spreadsheet in specific folder?


Solution

  • In general, these kinds of drive operations (create, copy, remove) do take a up to a couple seconds each.

    You can speed this up a bit, instead of copying the spreadsheet into your folder and then deleting the original, simply move the file into the folder:

     function create_ss_in_folder(folder, name) {
      var ss = SpreadsheetApp.create(name);
      var id = ss.getId();
      var file = DriveApp.getFileById(id);
      var folder = get_folder_by_name(folder);
      folder.addFile(file);
      DriveApp.getRootFolder().removeFile(file);
      return id;
    }
    

    see: https://developers.google.com/apps-script/reference/drive/folder

    This should save you a couple seconds.

    Another option is to use the Advanced Drive service, which should allow you to create a spreadsheet file directly inside the desired folder in one step. I'm not sure how much faster this would be.

    see: https://developers.google.com/apps-script/advanced/drive