Jack
Jack

Reputation: 2344

Google script API - How to create a google doc in a particular folder

Basically this question is giving an answer for what I'd like to do:

Google script to create a folder and then create a Google Doc in that folder

But it's 5 years old, and I was wondering if there was an easier way now. In my case I have lots of existing folders and I want to create a particular file in each of them via a script that runs at intervals.

Thx.

EDIT:

Ok, the code below works fine (using a modified sample script 1 in the answer) when the folder 'test folder' is in a shared drive.

function testFunction() {
  
  const notesFileName = 'test doc';
  const folderName = 'test folder';
  const query = "title = '" + folderName + "'";
  // Find all folders that match the query.
  var folders = DriveApp.searchFolders(query);
  while (folders.hasNext()) {
    // In all the sub-folders, of each found folder, create a file with the same name.
    var folder = folders.next();
    Logger.log("Found a folder: " + folder);
    var subFolders = folder.getFolders();
    while( subFolders.hasNext() ) {
      var subFolder = subFolders.next();
      Logger.log('Folder id: ' + subFolder.getId());
      const doc = Drive.Files.insert({title: notesFileName, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: subFolder.getId()}]}, null, {supportsAllDrives: true});
    }
  }
}

Upvotes: 0

Views: 647

Answers (1)

Tanaike
Tanaike

Reputation: 201388

I believe your goal as follows.

  • You want to create new Google Document to the specific folders.
  • You have a lot of folders you want to create new Google Document. So you want to reduce the process cost of the script.

In this case, I would like to propose to create the new Google Document using Drive API. When Drive API is used, the creation of Google Document to each folder can run with the asynchronous process. The sample script is as follows.

Sample script 1:

Before you use this script, please enable Drive API at Advanced Google services. In this sample script, the new Google Documents are created to the specific folders in a loop.

function sample1() {
  const titleOfDocument = "sample document";
  const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
  const documentIds = folderIds.map(id => Drive.Files.insert({title: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [{id: id}]}).id);
  console.log(documentIds)
}
  • In this script, the created Document IDs are returned.
  • If the process time of this script was long in your actual situation, please test the following sample script 2.

Sample script 2:

Before you use this script, please enable Drive API at Advanced Google services. In this sample script, the new Google Documents are created to the specific folders using the batch request of Drive API using a Google Apps Script library. By this, the tasks are run with the asynchronous process.

Please install the Google Apps Script library for using the batch request. Ref

function sample2() {
  const titleOfDocument = "sample document";
  const folderIds = ["### folder ID1 ###", "### folder ID 2 ###",,,];
  const requests = {
    batchPath: "batch/drive/v3",
    requests: folderIds.map(id => ({
      method: "POST",
      endpoint: `https://www.googleapis.com/drive/v3/files`,
      requestBody: {name: titleOfDocument, mimeType: MimeType.GOOGLE_DOCS, parents: [id]},
    })),
    accessToken: ScriptApp.getOAuthToken(),
  };
  const result = BatchRequest.EDo(requests); // Using GAS library
  const documentIds = result.map(({id}) => id);
  console.log(documentIds)
}

Note:

  • For above sample scripts, if you want to retrieve the folder IDs under the specific folder, you can also use for folderIds as follows.

      const topFolderId = "### top folder ID ###";
      const folders = DriveApp.getFolderById(topFolderId).getFolders();
      const folderIds = [];
      while (folders.hasNext()) {
        folderIds.push(folders.next().getId());
      }
    
  • By the way, in the current stage, in order to move the file, you can use moveTo(destination). Using this, the script of this can be modified as follows.

      function createDoc(folderID, name) {
        var folder = DriveApp.getFolderById(folderID);
        var doc = DocumentApp.create(name);
        DriveApp.getFileById(doc.getId()).moveTo(folder);
        return doc;
      }
    

References:

Upvotes: 1

Related Questions