Skip to content

Instantly share code, notes, and snippets.

@barrieroberts
Created January 5, 2022 12:06
Show Gist options
  • Save barrieroberts/e820340e881d98d70c67fff0db2dd171 to your computer and use it in GitHub Desktop.
Save barrieroberts/e820340e881d98d70c67fff0db2dd171 to your computer and use it in GitHub Desktop.
//Make reports in Google Docs from data in a Google Sheet, then email them as PDFs
function makeSendReports() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getActiveSheet();
const [header, ...data] = sh.getDataRange().getDisplayValues();
const group = header[0].split(" - ")[0];
const teacher = header[0].split(" - ")[1];
const docMaster = DriveApp.getFileById('12MEOOsfFrxsQzBXqDe0gOTacncpaDoykTuWgoT5rzqI');
const placeholders = ['#NAME#', '#GROUP#', '#TEACHER#', '#READING#', '#WRITING#', '#SPEAKING#', '#LISTENING#', '#OVERALL#'];
//Loop thru sheet data - Make report
data.forEach((row, r) => {
let studentName = row[0];
let reportCopy = docMaster.makeCopy(`Report - ${studentName}`);
let report = DocumentApp.openById(reportCopy.getId());
let body = report.getBody();
//Replace placeholders in report
placeholders.forEach((placeholder, p) => {
let studentData = [studentName, group, teacher, row[2], row[3], row[4], row[5], row[6]];
body.replaceText(placeholder, studentData[p]);
});
report.saveAndClose();
//Add report link to sheet and sent status
sh.getRange(r + 2, 8).setFormula(`=HYPERLINK("${reportCopy.getUrl()}";"REPORT")`);
sh.getRange(r + 2, 9).setValue("SENT");
//Send email
let reportPDF = report.getAs(MimeType.PDF);
MailApp.sendEmail(row[1],
`Report - ${studentName}`,
"Please find the report for this term. Best regards, Barrie Roberts",
{ attachments: [reportPDF] }
);
});
}
//Adding a menu to run the above script from
function onOpen() {
const ui = SpreadsheetApp.getUi();
ui.createMenu('REPORTS')
.addItem('Make and send reports', 'makeSendReports')
.addToUi();
}
//Just to show how to add another function in a library
function newFunctionAdded(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment