Make a bunch of documents with Google Script

I’ve got a Google spreadsheet with the last name in column B and the email address in column D. My goal is to make a bunch of blank Google docs,name them in a pattern, share them with individual students, and put them in a particular folder. I decided to go ahead and write the document IDs in column E and make them link to the documents as a kind of index.

function docMaker() {
  const folderId = 'putyouridhere';
  const parentFolder = DriveApp.getFolderById(folderId);//destination folder
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data");//source data
  const data = sheet.getDataRange().getValues();//get all the entries on the sheet
//LOOP IT
  data.forEach((student,index) =>{
    const lastName = student[1];
    const email = student[3]; 
    const docName = `${lastName} Freewriting Journal`;//file naming pattern
    const studentDoc = DocumentApp.create(docName);
    const studentDocId = studentDoc.getId();
    DriveApp.getFileById(studentDocId).moveTo(parentFolder);//move to parent folder
    DriveApp.getFileById(studentDocId).addEditor(email);//add editor
    const link = sheet.getRange('E'+(index+1));
    const stuDocUrl = studentDoc.getUrl();//GET URL 
      const richValue = SpreadsheetApp.newRichTextValue()
      .setText(studentDocId)
      .setLinkUrl(stuDocUrl)
      .build();
      link.setRichTextValue(richValue);//Make fancy functional link to the document with the file ID as the text
    }
  )
}

Now I want to transfer ownership of all those documents so I can remove myself entirely from all this.

Handily, I wrote the doc IDs into column E for just such an occasion.

function transferOwner(){
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("data");
  const data = sheet.getDataRange().getValues();
   data.forEach((student,index) =>{
    const docId = sheet.getRange('E'+(index+1)).getValue();
          DriveApp.getFileById(docId).setOwner('SOMEONE@middlebury.edu')
   })
}

Leave a Reply