5

I'm currently doing this:

//set active spreadsheet to my template
      var ss = SpreadsheetApp.openById("MYSHEETKEY");
      SpreadsheetApp.setActiveSpreadsheet(ss);


//duplicate active sheet and set a new name
       SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet().setName(rData[0][1]);

which is creating a new sheet in my template Spreadsheet, quite rightly. What I really need is to create an entirely new copy of the document as a whole, ideally in to a specified folder in my Google Drive. Is this possible?

Thanks as advance!

James
  • 83
  • 2
  • 6

1 Answers1

4

There is a copy() function. The docs are at: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#copy(String)

var ss = SpreadsheetApp.openById("MYSHEETKEY");
var newSS = ss.copy("Copy of " + ss.getName());
// Move to original folder
var originalFolder = DriveApp.getFileById("MYSHEETKEY").getParents().next();
var newSSFile = DriveApp.getFileById(newSS.getId());
originalFolder.addFile(newSSFile);
DriveApp.getRootFolder().removeFile(newSSFile);
Spencer Easton
  • 5,642
  • 1
  • 16
  • 25
  • Thanks very much for your advice. Works great, although I had to remove getParents() and next() .... can you please explain to me the purpose of these? – James May 21 '15 at 16:38
  • .getParents() returns the list of folders this file is in and next() gets the first folder. This code is assuming that the spreadsheet is only in one folder. – Spencer Easton May 21 '15 at 17:16
  • And you shouldn't have to remove those. The code above works. – Spencer Easton May 21 '15 at 17:55
  • Apologies, I confused myself for a moment there, I was indeed struggling to make the code work (I assume my own incompetence!) but in the end I tweaked that line to var targetFolder = DriveApp.getFolderById("MYFOLDERID"); - and then I removed the getParents & next(). Thanks again – James May 22 '15 at 08:22