user12176931
user12176931

Reputation:

How do I create Spreadsheet inside a specific folder?

Currently, based on certain parameters, I'm creating Spreadsheets using Apps Script via the following code -

function newFile() {
  var number = '1';
  var newFile = SpreadsheetApp.create("Roll " + number);
}

These new sheets however are being created at the root of Google Drive but instead, I want them to be created under a specific folder.

Unable to find any documentation for it. Any help would be appreciated.

Upvotes: 0

Views: 2124

Answers (1)

Tanaike
Tanaike

Reputation: 201613

  • You want to create a new Spreadsheet to the specific folder.
  • You want to achieve this using Google Apps Script.

If my understanding is correct, how about this answer? Please think of this as just one of several answers.

Pattern 1:

In this pattern, your script is modified. After the new Spreadsheet was created to the root folder, the Spreadsheet is moved to the specific folder.

Sample script:

var folderId = "###"; // Please set the folder ID.
var number = '1';
var fileName = "Roll " + number;

var number = '1';
var newFile = SpreadsheetApp.create("Roll " + number);

var folder = DriveApp.getFolderById(folderId);
var file = DriveApp.getFileById(newFile.getId());
DriveApp.getFolderById("root").removeFile(file);
folder.addFile(file);

Pattern 2:

In this pattern, the new Spreadsheet is directly created to the the specific folder using Drive API. When you use this script, please enable Drive API at Advanced Google services.

Sample script:

var folderId = "###"; // Please set the folder ID.
var number = '1';
var fileName = "Roll " + number;

var file = Drive.Files.insert({title: fileName, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: folderId}]});
var newFile = SpreadsheetApp.openById(file.id);

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 4

Related Questions