[GAS] How to copy a file from a template and create a new one (basic)

by

in

For example, if you want to create a new spreadsheet by copying a template file saved in Google Drive.

Get folder (.getFolderById)

First, get the folder in Google Drive. You can get the folder by using the .getFolderById method.

const OutputFolder = DriveApp.getFolderById('XXXXXXXXXXXXXX');

Store this value in a variable.

Get File (.getFolderById)

You can get the file by using the .getFolderById method.

 // テンプレートファイル
const templateFile = DriveApp.getFileById('XXXXXXXXXXXXX');

Copy the fileID of the file prepared in advance as a template file and paste it in the XXXXX part.

Store this value in a variable.

Create file name

Create a file name so that when you copy it, you know it’s a newly created file.

const date = Utilities.formatDate( new Date(), 'Asia/Tokyo', 'yyyyMMddHHmmss');
const OutputFileName = templateFile.getName().replace('A', 'B')+'_'+date;

First, get the current date and time with yyyyMMddHHmmss, then change the template file name to another file name (A: template file name, B: file name after change) and create with underscore & date time.

[rml_read_more]

Then the file name like this will be stored in the variable.

BBBBBBB_20220912102134
BBBBBBB_20220914112334
BBBBBBB_20220920112134
BBBBBBB_20220922112034

Make a copy (.makeCopy)

After that, create a file with the specified file name in the specified folder, and you are done.

templateFile.makeCopy(OutputFileName, OutputFolder);

This will copy a new, renamed file into the same folder.

summary

Now you can copy the file from the template to create a new one.

First of all, it was a basic and simple method, but I feel that various useful scenes will come out when combined with Google Forms, so please try it.