Create duplicate of Google Sheet in designated Drive directory

I’m trying to use Apps Script to duplicate a Google Sheet and save it in a specific folder. Here’s what I want to do:

  1. Make a new spreadsheet called ‘Spreadsheet_B’ in a folder named ‘myfolder’
  2. Copy the contents of ‘Spreadsheet_A’ into this new sheet

I’ve looked everywhere but can’t figure out how to do this. Can anyone help me with the right script? Here’s a basic outline of what I think it should do:

function copySpreadsheet() {
  var targetFolder = DriveApp.getFolderById('folderID');
  var newSheet = SpreadsheetApp.create('Spreadsheet_B');
  var sourceSheet = SpreadsheetApp.openById('sourceSheetID');
  
  // Need help with copying content here
  
  targetFolder.addFile(DriveApp.getFileById(newSheet.getId()));
}

Any guidance would be really appreciated!

I’ve actually done something similar recently for a work project. Here’s what worked for me:

Instead of creating a new spreadsheet and then copying content, it’s easier to duplicate the entire spreadsheet first, then move it to the desired folder. You can use the DriveApp.getFileById() method to get the original file, then use makeCopy() to create a duplicate.

Here’s a modified version of your script that should work:

function copySpreadsheet() {
  var sourceId = 'sourceSheetID';
  var folderId = 'folderID';
  var newName = 'Spreadsheet_B';

  var sourceFile = DriveApp.getFileById(sourceId);
  var targetFolder = DriveApp.getFolderById(folderId);
  var newFile = sourceFile.makeCopy(newName, targetFolder);

  // Optionally, you can open the new spreadsheet and make changes
  var newSheet = SpreadsheetApp.open(newFile);
}

This approach is more efficient and ensures all content, formatting, and sheets are copied correctly. Hope this helps!

hey josephk, i’ve done this before. try using the makeCopy() method on the source file. it’s easier than creating a new sheet and copying stuff over. something like:

sourceFile.makeCopy(‘Spreadsheet_B’, targetFolder);

this should copy everything in one go. lemme know if u need more help!