Copying a File with Apps Script

It is possible to easily create a copy of a Google Sheets document using Apps Script.


Copy in the Same Folder

To copy the current file in use to the same folder, execute this script:

function copyFile() {
  // Source: https://sheets-pratique.com/en/codes/file-copy
  const file = DriveApp.getFileById(SpreadsheetApp.getActive().getId());
  const newFileName = 'NEW_FILE_NAME';
  file.makeCopy(newFileName);
}

Or in a shorter version:

function copyFile() {
  // Source: https://sheets-pratique.com/en/codes/file-copy
  DriveApp.getFileById(SpreadsheetApp.getActive().getId()).makeCopy('NEW_FILE_NAME');
}
To copy a file other than the one currently in use, replace SpreadsheetApp.getActive().getId() with the ID of the file you want to copy.

Copy to Another Folder

To copy the current file in use to a different folder, replace FOLDER_ID with the ID of the target folder and execute this script:

function copyFile() {
  // Source: https://sheets-pratique.com/en/codes/file-copy
  const file = DriveApp.getFileById(SpreadsheetApp.getActive().getId());
  const folder = DriveApp.getFolderById('pA24kaHDVGdi66b9bjDqLiUSqh1qhd0J0');
  const newFileName = 'NEW_FILE_NAME';
  file.makeCopy(newFileName, folder);
}

Or in a shorter version:

function copyFile() {
  // Source: https://sheets-pratique.com/en/codes/file-copy
  DriveApp.getFileById(SpreadsheetApp.getActive().getId()).makeCopy('NEW_FILE_NAME', DriveApp.getFolderById('pA24kaHDVGdi66b9bjDqLiUSqh1qhd0J0'));
}

You can retrieve the ID of a folder by opening the folder in Google Drive:

https://drive.google.com/drive/folders/pA24kaHDVGdi66b9bjDqLiUSqh1qhd0J0

Then copy the ID found in its URL, in this example, the ID is:

pA24kaHDVGdi66b9bjDqLiUSqh1qhd0J0