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!

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

4 Comments

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?
.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.
And you shouldn't have to remove those. The code above works.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.