0% found this document useful (0 votes)
69 views

Apps Script Course Source Code

This document provides a summary of a Google Apps Script complete course that contains 14 sections and over 100 code examples. The sections cover topics like the Spreadsheet, Document, Drive, Gmail, Calendar, and Forms services. It also includes examples of JavaScript fundamentals, working with arrays and objects, loops, dates, and more. The source code examples demonstrate how to select cells, update content, add sheets, and more using the Spreadsheet service class.

Uploaded by

pantro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Apps Script Course Source Code

This document provides a summary of a Google Apps Script complete course that contains 14 sections and over 100 code examples. The sections cover topics like the Spreadsheet, Document, Drive, Gmail, Calendar, and Forms services. It also includes examples of JavaScript fundamentals, working with arrays and objects, loops, dates, and more. The source code examples demonstrate how to select cells, update content, add sheets, and more using the Spreadsheet service class.

Uploaded by

pantro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

Google Apps Script Complete Course

New IDE 100+ Examples

Section 1: Introduction to Getting Started with Google Apps Script 2

Section 2: JavaScript in the Cloud Google apps Script and JavaScript Basics of Code 3

Section 3: Google Apps Script Sheets Spreadsheet Service Class Spreadsheet 6

Section 4: Google Apps Script Document Service Class DocumentApp 17

Section 5: Google Apps Script Drive Service Class DriveApp 27

Section 6: Google Apps Script Gmail Service Class GmailApp Methods 34

Section 7: Introduction to Google Apps Script Calendar Service Class 42

Section 8: Google Apps Script Slides Service Class SlidesApp 47

Section 9: Google Apps Script Forms Service Class FormApp 53

Section 10: Google Workspace services 57

Section 11: Google Apps Script Common 63

Section 12: Mini Projects with Web Apps Create web app URLs using Google 68

Section 13: Create a WebApp API endpoint Google Apps Script Addon Project 77

Section 14: Apps Script Code Examples Questions and Sample Code 80

Google Apps Script Course Source Code - Laurence Svekis


2

Section 1: Introduction to Getting Started with


Google Apps Script
Source Code Create a Document using Google Apps Script

​ function createaDoc() {
​ const doc = DocumentApp.create('Test New Doc 1');
​ }

Source Code Create a WebApp

​ function createaDoc() {
​ const doc = DocumentApp.create(VAL);
​ }

​ function doGet(){
​ return HtmlService.createHtmlOutputFromFile('index');
​ }


​ function doGet1(){
​ return HtmlService.createHtmlOutput('hello 2');
​ }



​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <style>
​ body {
​ background :red;
​ }
​ </style>
​ </head>
​ <body>
​ <h1>Hello World</h1>
​ <script>
​ console.log('test');
​ </script>
​ </body>
​ </html>
3

Section 2: JavaScript in the Cloud Google apps


Script and JavaScript Basics of Code
Variables and Functions JavaScript Code examples

​ const GLOBAL_VAL = 'Hello World';


​ function test1(){
​ const a = 'value';
​ const b = `val1`;
​ const c = "val2";
​ //var d = 10;
​ let e = true;
​ e = false;
​ Logger.log(a,b,c,e,GLOBAL_VAL);
​ }
​ function test2(){
​ Logger.log(GLOBAL_VAL);
​ }

​ function test3(val,val1){
​ Logger.log(val,val1);
​ return `${val} ${5+5} ${val1}`;
​ }

​ function test4(){
​ const a = 'Hello';
​ const b = 'World';
​ const temp = test3(a,'World');
​ Logger.log(temp);
​ }

​ function test5(){
​ const temp = test3('Hi','Coders');
​ Logger.log(temp);
​ }

4

JavaScript Arrays and Objects Code Examples Fundamentals of JavaScript


Code

​ function output(){
​ const obj = {'first name':'Laurence','last':'Svekis','val1':'One','val2':'Two'};
​ let x = 1;
​ //Logger.log(obj['val'+1]);
​ //Logger.log(obj['val'+2]);
​ //Logger.log(obj.last);
​ //Logger.log(obj['first name']);
​ /*
​ Comment lines
​ Many lines
​ */
​ const arr = ['Laurence','Svekis','One'];
​ Logger.log(arr);

​ const myObj = {
​ 'first' : 'Laurence',
​ 'last' : 'Svekis',
​ 'fullName' : function(){
​ Logger.log('Get the full name');
​ return this.first + ' ' + this.last;
​ }
​ }
​ let fullN = myObj.fullName();
​ Logger.log(fullN);
​ const doc = DocumentApp.create('New Doc');
​ arr.push('New');
​ Logger.log(arr.length);
​ arr.reverse();
​ arr.sort();
​ const last = arr.pop();
​ Logger.log(last);
​ const first = arr.shift();
​ Logger.log(first);
​ arr.unshift('FIRST');
​ arr.push('LAST');
​ Logger.log(arr);


​ }

JavaScript Code examples loops forEach Arrays and Objects example Code

​ function output1(){
​ for(let i = 0;i<10;i++){
​ //Logger.log('Counter : '+i);
5

​ }
​ let x =0;
​ while(x < 10){
​ x++;
​ //Logger.log('Counter : '+x);
​ }
​ const arr = ['Laurence','Svekis','One'];
​ //Logger.log(arr.length);
​ for(let y=0;y<arr.length;y++){
​ //Logger.log(arr[y]);
​ }
​ arr.forEach((ele,index)=>{
​ ///Logger.log(ele,index);
​ })
​ const myArray = [];
​ for(let q=0;q<10;q++){
​ //let temp = `item ${q}`;
​ const temp = {
​ 'first' : 'Myname'+q,
​ 'last' : 'Laster'+q
​ };
​ myArray.push(temp);
​ }
​ //Logger.log(myArray);
​ myArray.forEach((person)=>{
​ //Logger.log(person.first + person.last);
​ })
​ const newArray = myArray;
​ newArray[2] = 'NEW ITEM';
​ myArray[5] = 'MY ARRAY HERE';
​ Logger.log(myArray);
​ Logger.log(newArray);

​ }

JavaScript Math JSON.parse JSON.stringify Date Methods Code Examples

​ function output2() {
​ const today = new Date();
​ //Logger.log(today);
​ const day = 1000 * 60 * 60 * 24;
​ const nextWeek = new Date(today.getTime() + (day * 7));
​ //Logger.log(nextWeek);

​ let a = 0.5;
​ Logger.log(Math.floor(a));
​ Logger.log(Math.ceil(a));
​ for (let i = 0; i < 100; i++) {
​ let ranNum = Math.floor(Math.random() * 10) + 1; //1-10
​ Logger.log(ranNum);
​ }

6

​ const myObj = {
​ 'first' : 'Laurence',
​ 'last' : 'Svekis'
​ }
​ const myStr = JSON.stringify(myObj);
​ Logger.log(myObj.first);
​ Logger.log(myStr);
​ const myObj2 = JSON.parse(myStr);
​ myObj2.first = 'John';
​ Logger.log(myObj2);
​ Logger.log(myObj);


​ }

Section 3: Google Apps Script Sheets Spreadsheet


Service Class Spreadsheet
Select Spreadsheet Cell Update content and Update Background Color
Source Code

​ function test1() {
​ var spreadsheet = SpreadsheetApp.getActive();
​ spreadsheet.getRange('A1').activate();
​ spreadsheet.getCurrentCell().setValue('Hello');
​ spreadsheet.getRange('B1').activate();
​ spreadsheet.getCurrentCell().setValue('World');
​ spreadsheet.getRange('A1:B1').activate();
​ spreadsheet.getActiveRangeList().setFontWeight('bold')
​ .setFontSize(20)
​ .setBackground('#0000ff');
​ spreadsheet.getRange('D1').activate();
​ spreadsheet.getCurrentCell().setValue('Done');
​ };

Get active Spreadsheet SpreadsheetApp.getActive Code Example

​ function test2(){
​ const ss = SpreadsheetApp.getActiveSpreadsheet();
​ Logger.log(ss.getUrl());
​ Logger.log(ss.getId());
​ Logger.log(ss.getName());
​ }

Select all Contents of Active Sheet Object - output in log row values Source

​ function testSheet1(){
7

​ const ss = SpreadsheetApp.getActiveSpreadsheet();
​ const sheet = ss.getActiveSheet();
​ const data = sheet.getDataRange();
​ const values = data.getValues();
​ values.forEach((val)=>{
​ Logger.log(val[1]);
​ })
​ Logger.log(values);
​ Logger.log(sheet.getName());
​ }

Select Sheets and Spreadsheet standalone Code Example

​ function test2(){
​ const url =
'https://docs.google.com/spreadsheets/d/1rrORyEVHbvl_8I44q-_iIpO2SuY79qBKo66NEfKwg24/';
​ const ss = SpreadsheetApp.openByUrl(url);
​ //const sheet = ss.getSheets()[1];
​ const sheet = ss.getSheetByName('New 3');
​ //sheet.setName('UPDATED 500');
​ if(sheet != null){
​ Logger.log(sheet.getIndex());
​ }else{
​ Logger.log(sheet);
​ }
​ }



​ function test1() {
​ const id = '1rrORyEVHbvl_8I44q-_iIpO2SuY79qBKo66NEfKwg24';
​ const ss = SpreadsheetApp.openById(id);
​ const sheets = ss.getSheets();
​ sheets.forEach((sheet,index)=>{
​ Logger.log(sheet.getName());
​ sheet.setName('Updated '+index);
​ })
​ Logger.log(sheets);
​ }

Add new Sheet to Spreadsheet check if it exists by Name Source Code

​ function makeNewOne(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheets = ss.getSheets();
​ Logger.log(sheets);
​ const newName = 'Sheet New';
​ let sheet = ss.getSheetByName(newName);
​ if(sheet == null){
8

​ sheet = ss.insertSheet();
​ sheet.setName(newName);
​ }
​ Logger.log(sheet.getIndex());

​ }

Getting Cells Select Range by A1 Notation Source Code


Example

​ function addColors(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheets()[0];
​ let counter = 0;
​ for(let i=1;i<51;i++){
​ let backColor = 'green';
​ for(let x=0;x<5;x++){
​ let val = 'A'.charCodeAt()+x;
​ let letterVal = String.fromCharCode(val);
​ Logger.log(letterVal);
​ counter++;
​ if((counter%2)==0){
​ backColor = 'pink';
​ }else{
​ backColor = 'yellow';
​ }
​ sheet.getRange(letterVal+i).setBackground(backColor);
​ }
​ }
​ }

Select Range update style and value of cell Source CODE example

​ function addColors2(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheets()[0];
​ let backColor = 'red';
​ let mySize = 10;
​ for(let rows = 1;rows<51;rows++){
​ for(let cols=1;cols<11;cols++){
9

​ let total = rows + cols;


​ if((total%2)==0){
​ backColor = 'red';
​ }else{
​ backColor = 'pink';
​ }
​ let range = sheet.getRange(rows,cols);
​ range.setBackground(backColor);
​ range.setFontColor('white');
​ range.setFontSize(mySize+cols);
​ range.setValue(total);
​ }
​ }
​ }

SetValues within Range of Cells Source Code Example getRange and


SetValues

​ function getMyRange(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheets()[0];
​ const range = sheet.getRange(1,4,2,2);
​ const data = range.getValues();
​ range.setValues([['test1','test2'],['test3','test4']]);
​ range.setBackground('blue');
​ Logger.log(data);

​ }

Get last row and Last Column of Sheet Data Source Code Example

​ function testData1(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const sheet = SpreadsheetApp.openById(id).getSheets()[0];
​ const lastCol = sheet.getLastColumn();
​ const lastRow = sheet.getLastRow();
​ const range = sheet.getRange(1,1,lastRow,lastCol);
​ const rangeData = sheet.getDataRange();
​ const lastCorner = sheet.getRange(lastRow,lastCol);
​ lastCorner.setBackground('red');
​ Logger.log(lastCorner.getValue());
​ Logger.log(rangeData.getValues());
​ Logger.log(lastCol,lastRow);
​ Logger.log(range.getValues());
​ }

Setting Active Ranges and Range dimensions Selection Source Code

​ function test2(){
10

​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ ss.setActiveSheet(ss.getSheets()[1]);
​ const sheet = ss.getActiveSheet();
​ const range = sheet.getRange('B2:G5');
​ const dimArr =
[range.getLastRow(),range.getNumRows(),range.getLastColumn(),range.getNumColumns()];
​ Logger.log(dimArr);

​ sheet.setActiveRange(range);
​ ///range.setBackground('yellow');
​ Logger.log(sheet.getName());
​ const selectedSel = sheet.getSelection();
​ const selRange = selectedSel.getActiveRange();
​ const data = selRange.getValues();
​ selRange.setBackground('purple');
​ Logger.log(data);

​ }

Copy and Paste Values into New Sheet Create a Sheet Code Example

​ function copyMe(){
​ const ss = SpreadsheetApp.getActiveSpreadsheet();
​ const sheet = ss.getActiveSheet();
​ const range = sheet.getActiveRange();
​ const data = range.getValues();
​ createASheet(data,ss,range);
​ range.setBackground('red');
​ }

​ function createASheet(data,ss,range){
​ const numSheets = ss.getSheets();
​ const sheetName = 'Sheet '+ numSheets.length;
​ let newSheet = ss.getSheetByName(sheetName);
​ if(newSheet == null){
​ newSheet = ss.insertSheet();
​ newSheet.setName(sheetName);
​ }else{
​ //newSheet.clearContents();
​ //newSheet.clearFormats();
​ newSheet.clear();
​ }
​ const newRange = newSheet.getRange(1,1,range.getNumRows(),range.getNumColumns());
​ newRange.setValues(data);
​ }

Add to UI menu options AddItem GetUI and Addto UI methods examples

​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
11

​ ui.createMenu('New Opts')
​ .addItem('first','first')
​ .addItem('two','second')
​ .addSeparator()
​ .addSubMenu(ui.createMenu('sub')
​ .addItem('first','third')
​ .addItem('two','fourth')
​ )
​ .addItem('five','fifth')
​ .addToUi();
​ }

​ function first(){
​ logOut('ran first');
​ }
​ function second(){
​ logOut('ran second');
​ }
​ function third(){
​ logOut('ran third');
​ }
​ function fourth(){
​ logOut('ran fourth');
​ }
​ function fifth(){
​ logOut('ran fifth');
​ }

​ function logOut(val){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
​ ss.appendRow([val]);
​ }

Custom Copy to Log Exercise Apps Script Code Example source code

​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('adv')
​ .addItem('copy','copytolog')
​ .addToUi();
​ }

​ function copytolog(){
​ const ss = SpreadsheetApp.getActiveSpreadsheet()
​ const sheet = ss.getActiveSheet();
​ const range = ss.getSelection().getActiveRange();
​ const data = range.getValues();
​ let sheetLog = ss.getSheetByName('log');
​ if(sheetLog == null){
​ sheetLog = ss.insertSheet();
​ sheetLog.setName('log');
​ }
12

​ const newRange = sheetLog.getDataRange();


​ const startRow = newRange.getLastRow() +1;
​ const setRange =
sheetLog.getRange(startRow,1,range.getNumRows(),range.getNumColumns());
​ setRange.setBackground('red');
​ setRange.setValues(data);
​ sheetLog.appendRow([startRow]);

​ }

UI Class Prompt and Alert Button Set and user inputs Code Example

​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('adv')
​ .addItem('alert','popUp1')
​ .addItem('prompt1','popUp2')
​ .addItem('prompt2','popUp3')
​ .addToUi();
​ }

​ function popUp3(){
​ const ui = SpreadsheetApp.getUi();
​ const rep = ui.prompt('Do you like Apps Script rate 1-5?',ui.ButtonSet.YES_NO_CANCEL);
​ logVal(rep.getSelectedButton());
​ if(rep.getSelectedButton() == ui.Button.YES){
​ logVal('YES User rated ' + rep.getResponseText());
​ }else if(rep.getSelectedButton() == ui.Button.NO){
​ logVal('NO User rated ' + rep.getResponseText());
​ }else{
​ logVal('User Cancel');
​ }
​ }


​ function popUp2(){
​ const ui = SpreadsheetApp.getUi();
​ const rep = ui.prompt('Tell me your name?');
​ logVal(rep.getSelectedButton());
​ if(rep.getSelectedButton() == ui.Button.OK){
​ logVal(rep.getResponseText());
​ }else{
​ logVal('Prompt Closed');
​ }
​ }



​ function popUp1(){
​ const ui = SpreadsheetApp.getUi();
​ const rep = ui.alert('confirm','Do you agree',ui.ButtonSet.YES_NO);
​ logVal(rep);
13

​ if(rep == ui.Button.YES){
​ logVal('yes was pressed');
​ }else{
​ logVal('no was pressed');
​ }
​ }

​ function logVal(val){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('log');
​ ss.appendRow([val]);
​ }

Generate Modal Dialogs HtmlService Html Output and Template File Output
Example

​ const GLVAL = 'Testing Global Value';




​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('adv')
​ .addItem('showModal1','modal1')
​ .addItem('showModal2','modal2')
​ .addItem('showModal3','modal3')
​ .addToUi();
​ }

​ function modal3(){
​ const ui = SpreadsheetApp.getUi();
​ const html = HtmlService.createHtmlOutput('<h1>Hello World</h1><p>Tested</p>');
​ html.setHeight(500);
​ html.setWidth(800);
​ ui.showDialog(html);
​ }

​ function modal2(){
​ const ui = SpreadsheetApp.getUi();
​ //const html = HtmlService.createHtmlOutput('<h1>Hello World</h1><p>Tested</p>');
​ const html = HtmlService.createHtmlOutputFromFile('temp');
​ html.setHeight(500);
​ html.setWidth(800);
​ ui.showModelessDialog(html,'Modeless');
​ }

​ function modal1(){
​ const ui = SpreadsheetApp.getUi();
​ //const html = HtmlService.createHtmlOutput('<h1>Hello World</h1><p>Tested</p>');
​ const html = HtmlService.createTemplateFromFile('temp1').evaluate();
​ ui.showModalDialog(html,'test 1');
​ }

14






​ function logVal(val){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('log');
​ ss.appendRow([val]);
​ }

​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <style>
​ body{
​ background:red;
​ }
​ </style>
​ </head>
​ <body>
​ <h1>Hello</h1>
​ <p>Testing</p>
​ <script>
​ document.querySelector('h1').innerHTML = 'JAVASCRIPT';
​ </script>
​ </body>
​ </html>
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <h1>Test 1</h1>
​ <?= GLVAL ?>
​ </body>
​ </html>

SideBar Saving values in Document Properties Store Code Example

​ const GLVAL = 'Testing Global Value';


​ let COUNTER = 0;


​ function onOpen(){
​ PropertiesService.getDocumentProperties().setProperty('cnt',0);
​ const ui = SpreadsheetApp.getUi();
15

​ ui.createMenu('adv')
​ .addItem('showSide1','side1')
​ .addItem('showSide2','side2')
​ .addItem('showSide3','side3')
​ .addToUi();
​ }

​ function side1(){
​ const ui = SpreadsheetApp.getUi();
​ const html = HtmlService.createHtmlOutput('<h1>Hello World</h1><p>Tested</p>');
​ ui.showSidebar(html);
​ }
​ function side2(){
​ const ui = SpreadsheetApp.getUi();
​ const html = HtmlService.createHtmlOutputFromFile('temp');
​ ui.showSidebar(html);
​ }
​ function side3(){
​ COUNTER = PropertiesService.getDocumentProperties().getProperty('cnt');
​ COUNTER++;
​ PropertiesService.getDocumentProperties().setProperty('cnt',COUNTER);
​ const ui = SpreadsheetApp.getUi();
​ const html = HtmlService.createTemplateFromFile('temp1').evaluate();
​ ui.showSidebar(html);
​ }

Insert Rows before and After Append Row Source Code Example Apps
Script

​ function addContent(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheetByName('test');
​ Logger.log(sheet);
​ let startPos = 5;
​ let startVal = sheet.getRange(startPos,1).getValue();
​ sheet.getRange(startPos,1).setValue(startVal + ' START');
​ sheet.insertRowAfter(startPos);
​ sheet.getRange(startPos+1,1).setValue('AFTER');
​ sheet.insertRowBefore(startPos);
​ sheet.getRange(startPos,1).setValue('BEFORE');
​ let tempArr = [sheet.getLastRow()+1,'test',2,'hello world'];
​ sheet.appendRow(tempArr);
​ }

Apps Script Create Custom Prepend Row Function Source Code

​ function prepender(val,sheet){
​ sheet.insertRowBefore(1);
​ let cloneArr = val.map((x)=>x);
16

​ cloneArr.push('START');
​ const range = sheet.getRange(1,1,1,cloneArr.length);
​ range.setValues([cloneArr]);
​ }

​ function addContent2(){
​ const id = '1looDMwg_ztAb2tiuRx6Xk3MXFtQ4yLc1vumVbiSnzu0';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheetByName('test');
​ let tempArr = [sheet.getLastRow()+1,'NEW CONTENT'];
​ prepender(tempArr,sheet);
​ tempArr.push('END');
​ sheet.appendRow(tempArr);

​ }

Run Custom Functions and set formulas within Spreadsheet Code Example

​ function SELVALA1(){
​ return SpreadsheetApp.getActive().getActiveRange().getA1Notation();
​ }

​ function addForm(){
​ const ss = SpreadsheetApp.getActive();
​ const sheet = ss.getSheetByName('test');
​ const range = sheet.getRange('C1:C15');
​ range.setFormula('=SUM(A1:B1)');
​ range.setFontColor('red');
​ range.setBackground('pink');

​ }

Selecting Active Cell and Adding Comments Source Code Example

​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('ADV')
​ .addItem('addComment','adder')
​ .addToUi();
​ }

​ function adder(){
​ const ui = SpreadsheetApp.getUi();
​ const cell = SpreadsheetApp.getActive().getActiveSheet().getActiveCell();
​ const rep = ui.prompt('What comment would you like to add?');
​ if(rep.getSelectedButton() == ui.Button.OK){
​ cell.setComment(rep.getResponseText());
​ }
​ }
17

Section 4: Google Apps Script Document Service


Class DocumentApp
Create a New Doc - Select Doc Object appendParagraph Apps Script Code
Example

​ function testDoc(){
​ const doc = DocumentApp.getActiveDocument();
​ const body = doc.getBody();
​ body.appendParagraph('Hello World');
​ body.appendPageBreak();
​ Logger.log(body);
​ }


​ function addtoDoc(){
​ const id = '1kDCr9jm1IovQ4GmpJYGDGToLmb6WZn6M679fF3Q6ZKU';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ body.appendParagraph('Hello World');
​ body.appendHorizontalRule();
​ body.appendPageBreak();
​ Logger.log(doc);
​ }

​ function createmyDoc(){
​ let myName = 'Tester Docs ';
​ const doc = DocumentApp.create(myName);
​ Logger.log(doc.getId());
​ Logger.log(doc.getUrl());
​ Logger.log(doc.getEditors());
​ myName += ' ' + doc.getId();
​ doc.setName(myName);
​ const body = doc.getBody();
​ body.appendParagraph('Hello World in '+myName);
​ body.appendParagraph('URL ' + doc.getUrl());
​ body.appendParagraph('NAME ' +doc.getName());
​ body.appendParagraph('Editors ' +doc.getEditors());
​ body.appendHorizontalRule();
​ body.appendPageBreak();

​ }

GetText contents from Doc body translate to Spanish LanguageApp Code


Example

​ function selContent(){
18

​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ const data = body.getText();
​ const paras = body.getParagraphs();
​ const spanVer = LanguageApp.translate(data,'en','es');
​ body.appendHorizontalRule();
​ body.appendParagraph('In Spanish');
​ body.appendHorizontalRule();
​ body.appendParagraph(spanVer);
​ Logger.log(paras);

​ }

​ function updateContent(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ for(let i=0;i<10;i++){
​ let temp = `${i}
​ 'Hello' "Hi" More text being added .....
​ `;
​ body.appendParagraph(temp);
​ }
​ }

DocumentApp Paragraphs Set Content and Manipulate Content Text Code


Example

​ function getParas(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ const paras = body.getParagraphs();
​ paras[0].setHeading(DocumentApp.ParagraphHeading.HEADING1);
​ paras.forEach((p,index)=>{
​ Logger.log(p.getTextAlignment());
​ Logger.log(p.getType());
​ let temp = p.getText();
​ temp = index + '. '+p.getType()+' '+p.getTextAlignment()+' '+ temp;
​ p.setText(temp);
​ p.setTextAlignment(DocumentApp.TextAlignment.NORMAL);
​ })
​ }

Get Element Container Children get Text and asText example Source Code

​ function getParas(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
19

​ const body = doc.getBody();


​ const paras = body.getParagraphs();
​ paras.forEach((p,index)=>{
​ //Logger.log(p.getNumChildren());
​ let temp = p.getText();
​ //p.appendText(' ' + index);
​ })
​ Logger.log(paras[2].getText());
​ Logger.log(paras[2].getNextSibling().asText().getText());
​ }

Update Font and Background Color of text Selection Code Example

​ function bodyEle(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ //Logger.log(body.getNumChildren());
​ for(let i=0;i<body.getNumChildren();i++){
​ //Logger.log(body.getChild(i));
​ let temp = body.getChild(i);
​ //Logger.log(temp.getType());
​ let contentInside = temp.asText().getText();
​ //Logger.log(contentInside);
​ if(temp.getType() == 'PARAGRAPH'){
​ let val = temp.asParagraph().editAsText().setFontSize(20);
​ if(temp.asParagraph().getText().length > 5){
​ let endPos = 3;
​ let startPos = 1;
​ val.setBackgroundColor(startPos,endPos,'#0000ff');
​ }
​ Logger.log(val);
​ //temp.asParagraph().insertText(1,' NEW '+i);
​ }
​ }
​ }

Selecting Text from Body Apply Bold Colors and Size to text with Doc
Example

​ function docContents(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ const txt = body.editAsText();
​ Logger.log(txt.getText().length);

txt.insertText(0,"#NEWCOLOR").setFontSize(0,8,30).setBackgroundColor(0,8,'#ff00ff').set
ForegroundColor(0,8,'#ffffff');
​ txt.insertText(20,"#NEWBOLD").setBold(20,27,true);
20

​ //val2.setBold(20,26,true);
​ Logger.log(txt);

​ }

Apply Style to Content within Doc Code Example Apps Script Doc

​ function addStyles(){
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const doc = DocumentApp.openById(id);
​ const body = doc.getBody();
​ const paras = body.getParagraphs();
​ //Logger.log(paras.length);
​ const style1 = {};
​ style1[DocumentApp.Attribute.FONT_SIZE] = 22;
​ style1[DocumentApp.Attribute.FOREGROUND_COLOR] = '#ffffff';
​ style1[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ff0000';
​ const style2 = {};
​ style2[DocumentApp.Attribute.FONT_SIZE] = 12;
​ style2[DocumentApp.Attribute.FOREGROUND_COLOR] = '#000000';
​ style2[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffffff';
​ paras.forEach((el,index)=>{
​ if(el.getText().length > 0 ){
​ Logger.log(el.getText().length);
​ Logger.log(el.getNumChildren());
​ Logger.log(el.getAttributes());
​ let val = el.appendText('NEW');
​ val.setAttributes(style1);
​ if(index==2){
​ el.setAttributes(style2);
​ }
​ }
​ })
​ }

​ /*
​ {HORIZONTAL_ALIGNMENT=null, LINE_SPACING=null, HEADING=Normal, BOLD=null,
LEFT_TO_RIGHT=true, BACKGROUND_COLOR=null, INDENT_END=null, INDENT_FIRST_LINE=null,
STRIKETHROUGH=null, LINK_URL=null, FONT_FAMILY=null, INDENT_START=null, UNDERLINE=null,
ITALIC=null, SPACING_AFTER=null, FONT_SIZE=12.0, SPACING_BEFORE=null,
FOREGROUND_COLOR=null}
​ */

Find Replace Text in Doc Highlight Text Selection Code Examples

​ function replacer(){
​ const style = {};
​ style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#0000ff';
​ style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffff00';
​ const id = '1u4hbYfNe64B2MTepfkWPA8j92HcaymFac6m0pni5RMk';
​ const body = DocumentApp.openById(id).getBody();
21

​ const rep = body.replaceText('(?i)Lorem','LAURENCE');



​ let founder = body.findText('LAURENCE');
​ while (founder != null){
​ let val = founder.getElement().asText();
​ Logger.log(val);
​ let start = founder.getStartOffset();
​ let end = founder.getEndOffsetInclusive();
​ Logger.log(start, end);

​ val.setBackgroundColor(start,end,'#ff0000');
​ val.setForegroundColor(start,end,'#ffffff');
​ //val.setAttributes(style);
​ founder = body.findText('LAURENCE',founder);
​ }

​ //Logger.log(founder);
​ //founder.getElement().setAttributes(style);

​ //rep.setAttributes(style);




​ }

Examples of regular expressions


https://support.google.com/a/answer/1371417?hl=en

Regex Generator https://regexr.com/

Docs Create List using List Id Google Apps Script Source Code

​ function addList(){
​ const body = DocumentApp.getActiveDocument().getBody();
​ //Logger.log(body.editAsText().getText());
​ const val1 = body.appendListItem('item 1');

​ Logger.log(val1.getListId());
​ //kix.uq8c9jsmuygr
​ body.appendParagraph('new list');
​ const val2 = body.appendListItem('item 2');
​ val2.setListId(val1);
​ Logger.log(val2.getListId());
​ for(let i=0;i<10;i++){
​ let val3 = body.appendListItem('item '+(i+2));
22

​ val3.setListId(val1);
​ }
​ }

Copy Text from one Doc to Another source code

​ // source 1ma0ccRNdl9CSsbbdxDKkkY9sANzgi2S8Ylf7NTHK6Pk
​ function addLorem(){
​ const id = '1ma0ccRNdl9CSsbbdxDKkkY9sANzgi2S8Ylf7NTHK6Pk';
​ const body = DocumentApp.getActiveDocument().getBody();
​ const sourceLorem = DocumentApp.openById(id).getBody();
​ body.clear();
​ const data = sourceLorem.getText();
​ body.appendParagraph(data);
​ }

DocumentApp Create Table Insert Sheet Data as Table Update Tables Style

​ function addTable(){
​ const style = {};
​ style[DocumentApp.Attribute.FOREGROUND_COLOR] = '#0000ff';
​ style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#ffff00';
​ const body = DocumentApp.getActiveDocument().getBody();
​ body.clear();
​ //const arr = [['col1','col2','col3'],['1','2','3'],['4','5','6']];
​ const arr = getData();
​ const val = body.appendTable(arr);
​ Logger.log(val);
​ const row = val.insertTableRow(4);
​ row.insertTableCell(0,'TEST1');
​ row.insertTableCell(1,'TEST2');
​ row.insertTableCell(2,'TEST3');
​ row.setAttributes(style);
​ }

​ function getData(){
​ const id = '18EiSL1V4IAWvVi0vJsKc_JEIK1_bF4Ulo3L3Wb716II';
​ const ss = SpreadsheetApp.openById(id).getSheets()[0];
​ const data = ss.getDataRange().getValues();
​ Logger.log(data);
​ return data;
​ }

UI ALert and UI Prompt Doc App Google Script Code Example

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('Adv')
​ .addItem('alert','popAlert')
23

​ .addSeparator()
​ .addItem('prompt','popPrompt')
​ .addToUi();
​ }

​ function popAlert(){
​ const ui = DocumentApp.getUi();
​ const rep = ui.alert('Do you like Docs',ui.ButtonSet.YES_NO_CANCEL);
​ let message = 'Why not - to bad';
​ if(rep == ui.Button.YES){
​ message = 'Great I\'m happy to hear that';
​ }
​ ui.alert(message);
​ }

​ function popPrompt(){
​ const ui = DocumentApp.getUi();
​ const rep = ui.prompt('Rate 1-5',ui.ButtonSet.OK);
​ if(rep.getSelectedButton() == ui.Button.OK){
​ let val = rep.getResponseText();
​ ui.alert('We got the rating '+val);
​ }else{
​ ui.alert('Why did you close it???');
​ }
​ }

Add menu Item to add Lorem Ipsum Text at Cursor Position Code Example

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('fun')
​ .addItem('Lorem ipsum','adder')
​ .addToUi();
​ }


​ function adder(){
​ const cursor = DocumentApp.getActiveDocument().getCursor();
​ const id = '1ma0ccRNdl9CSsbbdxDKkkY9sANzgi2S8Ylf7NTHK6Pk';
​ const sourceContent = DocumentApp.openById(id).getBody().getText();

​ if(cursor){
​ const val = cursor.insertText(sourceContent);
​ if(val){
​ //val.setBackgroundColor('#ff0000');
​ val.setBold(true);
​ }
​ }
​ }

24

Find Text and Highlight from Prompt User Input Code Example Doc Google
Script

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('fun')
​ .addItem('Lorem ipsum','adder')
​ .addItem('Highlighter','highlight')
​ .addToUi();
​ }


​ function highlight(){
​ const ui = DocumentApp.getUi();
​ const body = DocumentApp.getActiveDocument().getBody();
​ const rep = ui.prompt('Highlight What',ui.ButtonSet.OK_CANCEL);
​ if(rep.getSelectedButton() == ui.Button.OK){
​ let findThis = rep.getResponseText();
​ let searchMe = body.findText(findThis);
​ while(searchMe != null){
​ let val = searchMe.getElement().asText();
​ let start = searchMe.getStartOffset();
​ let end = searchMe.getEndOffsetInclusive();
​ val.setBackgroundColor(start,end,'#000000');
​ val.setForegroundColor(start,end,'#000fff');
​ searchMe = body.findText(findThis ,searchMe);
​ }


​ }

​ }




​ function adder(){
​ const cursor = DocumentApp.getActiveDocument().getCursor();
​ const id = '1ma0ccRNdl9CSsbbdxDKkkY9sANzgi2S8Ylf7NTHK6Pk';
​ const sourceContent = DocumentApp.openById(id).getBody().getText();

​ if(cursor){
​ const val = cursor.insertText(sourceContent);
​ if(val){
​ //val.setBackgroundColor('#ff0000');
​ val.setBold(true);
​ }
​ }
​ }

25

Doc Modal Popups HTML content Google Apps Script HTMLService


Example

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('adv')
​ .addItem('html Model','modal1')
​ .addItem('html ModalLess','modal2')
​ .addToUi();
​ }

​ function modal1(){
​ const output = '<h1>Hello World</h1>';
​ const html = HtmlService.createHtmlOutput(output)
​ .setWidth(600)
​ .setHeight(500);
​ DocumentApp.getUi().showModalDialog(html,'Title Popup');
​ }

​ function modal2(){
​ const html = HtmlService.createHtmlOutputFromFile('popup')
​ .setWidth(800)
​ .setHeight(400);
​ DocumentApp.getUi().showModelessDialog(html,'Title Modal');
​ }

HTML file contents into UI Sidebar Google Apps Script HTML Service
Example

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('Adv')
​ .addItem('html Modal','modal1')
​ .addItem('file Modal','modal2')
​ .addItem('html Sidebar','side1')
​ .addItem('file Sidebar','side2')
​ .addToUi();
​ }

​ function side1(){
​ const output = '<h1>Hello World</h1>';
​ const html = HtmlService.createHtmlOutput(output)
​ .setWidth(600)
​ .setHeight(500);
​ DocumentApp.getUi().showSidebar(html);
​ }


​ function side2(){
26

​ const html = HtmlService.createHtmlOutputFromFile('popup')


​ .setWidth(600)
​ .setHeight(500);
​ DocumentApp.getUi().showSidebar(html);
​ }


​ function modal1(){
​ const output = '<h1>Hello World</h1>';
​ const html = HtmlService.createHtmlOutput(output)
​ .setWidth(600)
​ .setHeight(500);
​ DocumentApp.getUi().showModalDialog(html,'Title Popup');
​ }

​ function modal2(){
​ const html = HtmlService.createHtmlOutputFromFile('popup')
​ .setWidth(600)
​ .setHeight(500);
​ DocumentApp.getUi().showModelessDialog(html,'Title Modal');
​ }

Insert Image at Cursor Position UrlFetchApp Example Google Apps Script

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('Adv')
​ .addItem('addImage','addImage')
​ .addToUi();
​ }

​ function addImage(){
​ const doc = DocumentApp.getActiveDocument();
​ const cursor = doc.getCursor();
​ const url = 'https://dummyimage.com/300x200/0fff00/f000ff';
​ const myImage = UrlFetchApp.fetch(url).getBlob();
​ cursor.insertInlineImage(myImage);

​ }


​ function insertImage(){
​ const body = DocumentApp.getActiveDocument().getBody();
​ const url = 'https://dummyimage.com/600x400/000/fff';
​ const myImage = UrlFetchApp.fetch(url).getBlob();
​ const img = body.insertImage(0,myImage);
​ Logger.log(img);
​ const img1 = body.appendImage(myImage);
​ }

27

Section 5: Google Apps Script Drive Service Class


DriveApp
Search Files in Specific Folder Code Example Google Apps Script

​ function listMyFiles(folder) {
​ const files = folder.getFiles();
​ while (files.hasNext()){
​ const file = files.next();
​ Logger.log(file.getName());
​ }
​ }

​ function filesinFolder(){
​ const id = '1VqomA-OF_Gd8j20fZB1f5YiddQdIyuzL';
​ const folder = DriveApp.getFolderById(id);
​ listMyFiles(folder);

​ }

Create a file Create a folder within a folder Apps Script Code Example

​ function makeIt(){
​ const html = '<h1>Hello World</h1>';
​ const id = '1VqomA-OF_Gd8j20fZB1f5YiddQdIyuzL';
​ const folder = DriveApp.getFolderById(id);
​ const newFolder = folder.createFolder('New Folder');
​ newFolder.createFile('New HTML File',html,MimeType.HTML);
​ }

Get Drive Limit and Data used Apps Script Code Example

​ function driveDetails(){
​ const drive1 = DriveApp.getStorageLimit();
​ const drive2 = DriveApp.getStorageUsed();
​ Logger.log(drive2/drive1 *100);
​ }

Send Files into trash Recover and move files out of trash Apps
Script Example
28

​ function movetoTrashFiles(){
​ const files = DriveApp.getFilesByName('New HTML File');
​ while (files.hasNext()){
​ const file = files.next();
​ const today = new Date();
​ const fileInfo = {};
​ const fileDate = file.getLastUpdated();
​ fileInfo.active = today - fileDate;
​ fileInfo.nameFile = file.getName();
​ fileInfo.fileType = file.getMimeType();
​ const hour1 = 1000 * 60 * 60;
​ Logger.log(hour1);
​ if(fileInfo.active < hour1){
​ file.setTrashed(true);
​ }
​ Logger.log(fileInfo);
​ }
​ }

​ function getFromTrash(){
​ const files = DriveApp.getTrashedFiles();
​ while (files.hasNext()){
​ const file = files.next();
​ const today = new Date();
​ const fileInfo = {};
​ const fileDate = file.getLastUpdated();
​ fileInfo.active = today - fileDate;
​ const hour1 = 1000 * 60 * 60;
​ Logger.log(hour1);
​ if(fileInfo.active < hour1){
​ file.setTrashed(false);
​ }
​ }



​ }

Set File Access and permissions to Files and Folders with Script AddEditors

​ function myFiles(){
​ const id = '1j0DLOdUARddc1PueTzelZh85nllT4-dg';
​ const folder = DriveApp.getFolderById(id);
​ const files = folder.getFiles();
​ while (files.hasNext()){
​ const file = files.next();
​ const editors = file.getEditors();
​ Logger.log('*****'+file.getName()+'*****');
29

​ editors.forEach((editor)=>{
​ outputDriveUser(editor);
​ file.removeEditor(editor.getEmail());
​ })
​ file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);//Access
Permissions - Permission type
​ file.addViewer('education2learning@gmail.com'); //Permission for file
​ }
​ }


​ function myPermissions(){
​ const id = '1j0DLOdUARddc1PueTzelZh85nllT4-dg';
​ const folder = DriveApp.getFolderById(id);
​ const editors = folder.getEditors();

​ editors.forEach((editor)=>{
​ outputDriveUser(editor)
​ })
​ const viewers = folder.getViewers();
​ viewers.forEach((person)=>{
​ outputDriveUser(person);
​ })
​ const owner = folder.getOwner();
​ outputDriveUser(owner);
​ }


​ function outputDriveUser(user){
​ Logger.log(user.getEmail());
​ Logger.log(user.getName());
​ }

Get Files and Create PDF from files getAs create a blob code example

​ function createaPDF(){
​ const id = '1j0DLOdUARddc1PueTzelZh85nllT4-dg';
​ const folderSource = DriveApp.getFolderById(id);
​ const folderDes = DriveApp.createFolder('PDF');
​ const files = folderSource.getFiles();
​ while (files.hasNext()){
​ const file = files.next();
​ const blobFile = file.getAs('application/pdf');
​ blobFile.setName('PDF '+file.getName()+'.pdf');
​ const newFile = folderDes.createFile(blobFile);
​ Logger.log(newFile.getUrl());
​ }
​ }

List file details into new Spreadsheet Using Apps Script Code
30

​ function getDetails(){
​ const id = '1hGsVI-FJ3fcsNsNE7lFSMvHwV04k352m';
​ const folder = DriveApp.getFolderById(id);
​ const files = folder.getFiles();
​ const ss = SpreadsheetApp.create(folder.getName());
​ const sheet = ss.insertSheet('File Info');
​ const ssid = ss.getId();
​ ss.appendRow(['URL','Size','Download','id']);
​ while (files.hasNext()){
​ const file = files.next();
​ const fileInfo = [];
​ fileInfo.push(file.getUrl());
​ fileInfo.push(file.getSize());
​ fileInfo.push(file.getDownloadUrl());
​ fileInfo.push(file.getId());
​ Logger.log(fileInfo);
​ ss.appendRow(fileInfo);
​ }
​ }

Move all files within a Folder to New folder Create a Sheet and move to
folder

​ function moveFiles(){
​ const id = '1hGsVI-FJ3fcsNsNE7lFSMvHwV04k352m';
​ const srcFolder = DriveApp.getFolderById(id);
​ const endFolder = DriveApp.createFolder('moved');
​ const files = srcFolder.getFiles();
​ while (files.hasNext()){
​ const file = files.next();
​ endFolder.addFile(file);
​ }
​ }

​ function moveCreate(){
​ const ss = SpreadsheetApp.create('New File');
​ const folders = DriveApp.getFoldersByName('moved');
​ const ssid = ss.getId();
​ const file = DriveApp.getFileById(ssid);
​ if(folders.hasNext()){
​ let folder = folders.next();
​ folder.addFile(file);
​ }
​ Logger.log(file);
​ }

Search Drive for files return object info about file details Apps Script Code

​ function searcher(val){
​ const id = '1_K6euAToeLOTJqfM1uNtzickbtJi8VIx';
31

​ const folder = DriveApp.getFolderById(id);


​ const result = folder.searchFiles('title contains "'+val+'"');
​ //const result = DriveApp.searchFiles('title contains "'+val+'"');
​ const res = [];
​ while (result.hasNext()){
​ const file = result.next();
​ const results = {};
​ results.id = file.getId();
​ results.url = file.getName();
​ results.size = file.getSize();
​ results.owner = file.getOwner();
​ results.type = file.getMimeType();
​ res.push(results);
​ }
​ return res;
​ }


​ function startSearch(){
​ const searchTerm = 'new';
​ const found = searcher(searchTerm);
​ Logger.log(found);
​ }

https://developers.google.com/drive/api/v2/ref-search-terms

Operator Usage

contains The content of one string is present in the other.

= The content of a string or boolean is equal to the other.

!= The content of a string or boolean is not equal to the other.

< A value is less than another.

<= A value is less than or equal to another.

> A value is greater than another.

>= A value is greater than or equal to another.

in An element is contained within a collection.


32

and Return items that match both queries.

or Return items that match either query.

not Negates a search query.

has A collection contains an element matching the parameters.

Term Valid operators Usage

title contains1, =, != Name of the file. Surround with single quotes '. Escape
single quotes in queries with \', e.g., 'Valentine\'s Day'.

fullText contains2 3 Full text of the file including title, description, content,
and indexable text. Whether the 'title', 'description', or 'indexableText'
properties, or the content of the file matches. Surround with single quotes '.
Escape single quotes in queries with \', e.g., 'Valentine\'s Day'.

mimeType contains, =, != MIME type of the file. Surround with single quotes
'. Escape single quotes in queries with \', e.g., 'Valentine\'s Day'.

modifiedDate <=, <, =, !=, >, >= Date of the last modification of the file. RFC
3339 format, default timezone is UTC, e.g., 2012-06-04T12:00:00-08:00.
Fields of type date are not currently comparable to each other, only to
constant dates.

lastViewedByMeDate <=, <, =, !=, >, >= Date that the user last viewed a file.
RFC 3339 format, default timezone is UTC, e.g.,
2012-06-04T12:00:00-08:00. Fields of type date are not currently
comparable to each other, only to constant dates.

trashed =, != Whether the file is in the trash or not. Can be either true or
false.
33

starred =, != Whether the file is starred or not. Can be either true or false.

parents in Whether the parents collection contains the specified ID.

owners4 in Users who own the file.

writers4 in Users or groups who have permission to modify the file. See
Permissions resource reference.

readers4 in Users or groups who have permission to read the file. See
Permissions resource reference.

sharedWithMe =, != Files that are in the user's "Shared with me" collection.
All file users are in the file's access control list (ACL). Can be either true or
false.

properties has Public custom file properties.

visibility =, '!=' The visibility level of the file. Valid values are anyoneCanFind,
anyoneWithLink, domainCanFind, domainWithLink, and limited. Surround
with single quotes '. Escape single quotes in queries with \', e.g.,
'Valentine\'s Day'.

Coding App Challenge Spreadsheet track GDrive Files from Search Coding
Project

​ function onOpen(){
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('adv')
​ .addItem('search','findDrive')
​ .addToUi();
​ }

​ function findDrive(){
​ const ui = SpreadsheetApp.getUi();
​ const res = ui.prompt('Search','Search for what',ui.ButtonSet.OK_CANCEL);
​ if (res.getSelectedButton() == ui.Button.OK){
​ const searchTerm = res.getResponseText();
​ Logger.log(searchTerm);
​ const results = searchDrive(searchTerm);
34

​ if(results){
​ results.forEach((data)=>{
​ Logger.log(data);
​ addtoSheet(data);
​ })
​ }
​ }
​ }

​ function addtoSheet(data){
​ const ss = SpreadsheetApp.getActive().getSheetByName('results');
​ ss.appendRow(data);
​ }

​ function searchDrive(val){
​ const results = DriveApp.searchFiles('title contains "'+val+'"');
​ const ret = [];
​ while (results.hasNext()){
​ const file = results.next();
​ const temp = [file.getName(),file.getOwner(),file.getUrl()];
​ ret.push(temp);
​ }
​ return ret;
​ }

Section 6: Google Apps Script Gmail Service Class


GmailApp Methods
Send Email using Apps Script Code Example

​ function sendMyEmail(){
​ const email = 'gappscourses@gmail.com';
​ const subject = 'Test Email Script';
​ const body ='Hi This is an email';
​ GmailApp.sendEmail(email,subject,body);
​ }

​ function sendMyEmail2(){
​ const email = 'gappscourses@gmail.com';
​ const subject = 'Test Email Script 2';
​ const body ='Hi This is an email 2';
​ MailApp.sendEmail(email,subject,body);
​ }

Send Email MailService Send Attachment Add options HTML Emails


MailApp Service

​ function mailService(){
35

​ const quotaVal = MailApp.getRemainingDailyQuota();


​ Logger.log(quotaVal);
​ }

​ function sendMyEmail1(){
​ const email = Session.getActiveUser().getEmail();
​ Logger.log(email);
​ const subject = 'Test Email';
​ const html = '<h1>Hello World</h1>'
​ const obj = {
​ to:email,
​ subject:subject,
​ htmlBody:html};
​ MailApp.sendEmail(obj);
​ }

​ function sendMyEmail3(){
​ const email = Session.getActiveUser().getEmail();
​ const subject = 'Test Email Attachment 3';
​ const html = '<h1>Hello World</h1>'
​ const id = '1pBcphLBsVcps0nsrAjH6bo8HvV4T1dS1';
​ const file = DriveApp.getFileById(id);
​ const opts = {
​ name:'My File',
​ cc:email,
​ noReply: true,
​ replyTo: 'test@gmail.com',
​ htmlBody:html,
​ attachments:[file.getAs(MimeType.PDF)]};
​ MailApp.sendEmail(email,subject,'',opts);
​ }

Send and Create Draft emails with GmailApp Services Code Example Apps
Script

​ function sendanEmail1(){
​ const email = Session.getActiveUser().getEmail();
​ const subject = 'Test Email Attachment 4';
​ const html = '<h1>Hello World</h1>'
​ const id = '1pBcphLBsVcps0nsrAjH6bo8HvV4T1dS1';
​ const file = DriveApp.getFileById(id);
​ const opts = {
​ name:'My File',
​ htmlBody:html,
​ attachments:[file.getAs(MimeType.PDF)]};
​ GmailApp.sendEmail(email,subject,'',opts);
​ }

​ function makeDraft(){
​ const email = Session.getActiveUser().getEmail();
​ const subject = 'Test Email 5';
36

​ const html = '<h1>Hello World</h1>'


​ GmailApp.createDraft(email,subject,'',{htmlBody:html})
​ }

​ function getDrafts(){
​ const drafts = GmailApp.getDrafts();
​ //Logger.log(drafts[0]);
​ for(let i=0;i<drafts.length;i++){
​ //Logger.log(drafts[i]);
​ }
​ drafts.forEach((draft)=>{
​ Logger.log(draft.getMessage());
​ let message = draft.getMessage();
​ if(message.getSubject() == 'Test Email 5'){
​ draft.send();
​ }
​ Logger.log(message.getSubject());
​ //Logger.log(draft.getId());
​ })
​ }

Send Replies Check Threads inbox if Read Get Messages Apps Script Gmail
Service

​ function getmyThreads(){
​ const unread = GmailApp.getInboxUnreadCount();
​ //Logger.log(unread)
​ const threads = GmailApp.getInboxThreads();
​ //Logger.log(threads);
​ threads.forEach((thread)=>{
​ //Logger.log(thread.getId());
​ //Logger.log(thread.getMessageCount());
​ if(thread.isUnread()){
​ const messages = thread.getMessages();
​ thread.reply('Got the message - I read it - Thread');
​ let val = 0;
​ messages.forEach((message)=>{
​ Logger.log(message.getSubject());
​ val++;
​ message.reply('Reply on Message '+val,{
​ htmlBody:'<h1>wow HTML '+val+'</h1>'
​ });
​ })
​ Logger.log(thread.getId());
​ thread.markRead();
​ }
​ })
​ }

37

Create Email from HTML template file - replace and update content Apps
Script

​ function emailTempSender(){
​ const html = '<h1>Wow HTML is here</h1>';
​ let htmlBody = HtmlService.createHtmlOutputFromFile('email').getContent();
​ htmlBody = htmlBody.replace(/#TITLE/g,'Custom title');
​ htmlBody = htmlBody.replace(/#MESSAGE/g,'Custom message');
​ htmlBody = htmlBody.replace(/#NAME/g,'USER name');
​ const email = Session.getActiveUser().getEmail();
​ const subject = 'HTML Custom Message';
​ const prop = {
​ htmlBody : htmlBody
​ };
​ GmailApp.sendEmail(email,subject,'',prop);

​ }

HTML file as EMail Template Source Code Apps Script Example

​ function sendHTMLtemp(){

//https://docs.google.com/document/d/1_CzyhBlVdw3rUWyFubnm9zzfIGsniMmDpcT6c4T8OPk/expor
t?format=html
​ const id = '1_CzyhBlVdw3rUWyFubnm9zzfIGsniMmDpcT6c4T8OPk';
​ const url = 'https://docs.google.com/document/d/'+id+'/export?format=html';
​ const param ={
​ mehtod : "get",
​ headers : {
​ "Authorization":"Bearer "+ScriptApp.getOAuthToken()
​ },
​ muteHttpExceptions:true
​ }
​ let html = UrlFetchApp.fetch(url,param);
​ html = html.getContentText();
​ html = html.replace(/#USER/g, 'Laurence');
​ html = html.replace(/#MYNAME/g, 'Svekis Teacher');
​ const email = Session.getActiveUser().getEmail();
​ const subject = 'HTML from DOC '+id;
​ const prop = {
​ htmlBody:html
​ };
​ Logger.log(html);
​ GmailApp.sendEmail(email,subject,'',prop);
​ }

Project Send Emails from Spreadsheet List MailService Code Example


Apps Script
38

​ function sender(){
​ const id = '14KNTH7qzgQuYRodf_zvJDThrLkoKW4BgE1jG8Eld8wI';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheetByName('emails');
​ const data = sheet.getDataRange().getValues();
​ //Logger.log(data);
​ const people = data.slice(1);
​ //Logger.log(people);
​ people.forEach((person,index)=>{
​ Logger.log(person);
​ const start = index + 2;
​ sendMyEmails(person);
​ const updateRange = sheet.getRange(start,7,1,1);
​ updateRange.setValues([['sent']]);
​ })
​ }

​ function sendTester(){
​ const myArr =['id','Laurence',"svekis",'Teacher','test','gappscourses@gmail.com'];
​ sendMyEmails(myArr);
​ }

​ function sendMyEmails(person){
​ const email = person[5];
​ Logger.log(email);
​ let htmlBody = HtmlService.createHtmlOutputFromFile('email').getContent();
​ htmlBody = htmlBody.replace(/#TITLE/g,person[3]);
​ htmlBody = htmlBody.replace(/#FIRST/g,person[1]);
​ htmlBody = htmlBody.replace(/#LAST/g,person[2]);
​ htmlBody = htmlBody.replace(/#MESSAGE/g,person[4]);
​ MailApp.sendEmail(email,'From List','',{
​ htmlBody : htmlBody
​ })
​ }

Check if text in message subject star and unstar messages Apps Script
Example

​ function messageStars(){
​ const emails = GmailApp.getInboxThreads();
​ emails.forEach((thread)=>{
​ //Logger.log(thread);
​ const messages = thread.getMessages();
​ messages.forEach((message)=>{
​ const finder = 'alert';
​ const test = message.getSubject().includes(finder);
​ //Logger.log(test);
​ if(test && message.isStarred()){
​ message.unstar();
​ }else if(test){
​ Logger.log(message.getSubject());
39

​ message.star();
​ }
​ //const hasStar = message.isStarred();
​ //Logger.log(hasStar);

​ })
​ })
​ }

Add Labels Create Labels remove Labels from Threads GmailApp Example
Code

​ function testLabels(){
​ const myName = 'NewLabelTester';
​ const myLabel = GmailApp.getUserLabelByName(myName);
​ Logger.log(myLabel);
​ if(myLabel){
​ const emails = GmailApp.getInboxThreads();
​ emails.forEach((thread)=>{
​ Logger.log(thread.getFirstMessageSubject());
​ const val = thread.getFirstMessageSubject();
​ if(val.includes('Attachment')){
​ //thread.addLabel(myLabel);
​ thread.removeLabel(myLabel);
​ }
​ })
​ }
​ }

​ function getallTest(){
​ const threads = GmailApp.getUserLabelByName('Test').getThreads();
​ threads.forEach((thread)=>{
​ Logger.log(thread.getFirstMessageSubject());
​ })
​ }


​ function addTestLabel(){
​ let val = 'Test';
​ let myLabel = GmailApp.getUserLabelByName(val);
​ if(myLabel == null){
​ myLabel = GmailApp.createLabel(val);
​ }
​ const emails = GmailApp.getInboxThreads();
​ emails.forEach((thread)=>{
​ const first = thread.getFirstMessageSubject();
​ if(first.includes(val)){
​ thread.addLabel(myLabel);
​ }
​ })
​ }
40





​ function createmyLabel(){
​ const myName = 'NewLabelTester';
​ const myLabel = GmailApp.createLabel(myName);
​ Logger.log(myLabel);
​ }

Get GmailApp Chat Threads Code Example Apps Script

​ function chatThreads(){
​ const threads = GmailApp.getChatThreads(0,2);
​ Logger.log(threads);
​ threads.forEach((thread)=>{
​ Logger.log(thread.getMessageCount());
​ const messages = thread.getMessages();
​ messages.forEach((message)=>{

​ })
​ })


​ }

GmailApp Search emails search operators for GmailApp Search Code


Example

​ function searchInbox(){
​ const results = GmailApp.search('has:attachment',0,2);
​ Logger.log(results);
​ results.forEach((thread)=>{
​ Logger.log(thread);
​ const messages = thread.getMessages();
​ messages.forEach((message)=>{
​ Logger.log(message.getRawContent());
​ })
​ })

​ }

https://support.google.com/mail/answer/7190?hl=en
41

GmailApp Attachment Class Get Attachments Copy Attachment to Drive


Code Example

​ function searchInbox(){
​ const results = GmailApp.search('has:attachment',0,5);
​ //Logger.log(results);
​ let counter = 0;
​ results.forEach((thread)=>{
​ //Logger.log(thread);
​ const messages = thread.getMessages();
​ messages.forEach((message)=>{
​ const attachments = message.getAttachments();
​ //Logger.log(attachments);
​ attachments.forEach((data)=>{
​ Logger.log(data.getName());
​ Logger.log(data.getContentType());
​ if(data.getContentType() == 'application/pdf'){
​ const pdf = data.getAs('application/pdf');
​ counter++;
​ const newFile = DriveApp.createFile(pdf);
​ newFile.setName('NEW PDF '+counter+'.pdf');
​ }
​ })
​ })
​ })

​ }

GmailApp Classes Examples Draft Attachment Message Thread and Label


Classes

​ function tester(){
​ const val = GmailApp.getStarredThreads();
​ const myLabels = GmailApp.getUserLabels();
​ myLabels.forEach((label)=>{
​ Logger.log(label.getName());
​ })
​ const createDraftMessage = GmailApp.createDraft('test@gmail.com','Subjet','Body');
​ Logger.log(createDraftMessage );
​ val.forEach((thread)=>{
​ Logger.log(thread);
​ thread.addLabel(myLabels[0]);
​ })
​ }
42

Section 7: Introduction to Google Apps Script


Calendar Service Class
Select all Calendars get calendar details

​ function getMyCalendars(){
​ const cals = CalendarApp.getAllCalendars();
​ //Logger.log(cals);
​ const today = new Date();
​ cals.forEach((myCal)=>{
​ const myName = {
​ name: myCal.getName(),
​ id:myCal.getId(),
​ color :myCal.getColor(),
​ val:myCal.getEventsForDay(today)
​ };
​ Logger.log(myName);
​ Logger.log(myName.val.length);
​ })

​ }

Selecting Calendars using CalendarApp Class Code example

​ function getSomeCals(){
​ const cals0 = CalendarApp.getAllCalendars();
​ cals0.forEach((cal)=>{
​ Logger.log(cal.getId());
​ })
​ const cals1 = CalendarApp.getAllOwnedCalendars();
​ cals1.forEach((cal)=>{
​ Logger.log(cal.getName());
​ })
​ Logger.log('*****NAME*****');
​ const cals2 = CalendarApp.getCalendarsByName('test');
​ cals2.forEach((cal)=>{
​ Logger.log(cal.getName());
​ })
​ const calId = CalendarApp.getDefaultCalendar().getId();
​ Logger.log(calId);

​ const id = '662194ndtkusm80ivl7lql0rvc@group.calendar.google.com';
​ const cal1 = CalendarApp.getCalendarById(id);
​ Logger.log(cal1.getName());
43



​ }

Delete create and hide calendar Update and set New Name Calendar

https://developers.google.com/apps-script/reference/calendar/color.html

​ function makeCal(){
​ const cal = CalendarApp.createCalendar('New Calendar Today');
​ Logger.log(cal.getId());
​ cal.setColor('#00ff00');
​ cal.setDescription('this is a test calendar');
​ cal.setName('Updated Name');
​ }

​ function updateCal(){
​ const id = '6aq9ielvkjb2o1m56gkfnngd7o@group.calendar.google.com';
​ const cal = CalendarApp.getCalendarById(id);
​ Logger.log(cal.getDescription());
​ Logger.log(cal.getColor());
​ cal.setColor('#AB8B00');
​ cal.setHidden(false);
​ }

​ function delCal(){
​ const id = '6aq9ielvkjb2o1m56gkfnngd7o@group.calendar.google.com';
​ const cal = CalendarApp.getCalendarById(id);
​ cal.deleteCalendar();

​ }

Select and Update Calendar Events CalendarApp Event Class Examples

​ function getMyEvents(){
​ const cal = CalendarApp.getDefaultCalendar();
​ Logger.log(cal.getName());
​ const start = new Date();
​ const end = new Date(start.getTime() + (1000*60*60*24*7));
​ Logger.log(start.getTime());
​ const events = cal.getEvents(start,end);
​ events.forEach((event)=>{
​ Logger.log(event.getTitle());
​ event.setColor("3");
​ Logger.log(event.getId());
​ })
​ }
44


​ function updateEvent(){
​ const id = '4mv0mgb8kobpmensaukrs5fh5j@google.com';
​ const event = CalendarApp.getEventById(id);
​ event.setGuestsCanModify(true); //Guest permissions
​ event.setDescription('new description');
​ event.setLocation('My Home');
​ //event.setMyStatus(CalendarApp.GuestStatus.NO);
​ event.setVisibility(CalendarApp.Visibility.PUBLIC);
​ event.setTag('test','yes');
​ }

Create Events

​ function makeEvents3(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const futureDate = new Date(today.getTime() + (1000*60*60*24*4));
​ const endDate = new Date(today.getTime() + (1000*60*60*24*4)+(1000*60*60*2));
​ const opts = {
​ location : 'MY HOME',
​ guests : 'education2learning+1@gmail.com',
​ description : 'The party',
​ sendInvites: true
​ }
​ const rec = CalendarApp.newRecurrence().addWeeklyRule();
​ const event1 = cal.createAllDayEventSeries('Weekly Meet',today,rec);
​ const event2 = cal.createEventSeries('Series Weekly',futureDate,endDate,rec);
​ const event3 = cal.createEventSeries('Series Weekly',futureDate,endDate,rec,opts);

​ }


​ function makeEvents2(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const futureDate = new Date(today.getTime() + (1000*60*60*24*2));
​ const endDate = new Date(today.getTime() + (1000*60*60*24*4)+(1000*60*60*6));
​ const opts = {
​ location : 'MY HOME',
​ guests : 'education2learning+1@gmail.com',
​ description : 'The party',
​ sendInvites: true
​ }
​ const event1 = cal.createEvent('My Next Test 2',futureDate,endDate)
​ event1.setColor('2');
​ const event2 = cal.createEvent('With Options',futureDate,endDate,opts);
​ event2.addGuest('education2learning+2@gmail.com');
​ }


​ function makeEvents(){
45

​ const cal = CalendarApp.getDefaultCalendar();


​ //cal.createEventFromDescription('test 1, Monday at 4pm');
​ const today = new Date();
​ const futureDate = new Date(today.getTime() + (1000*60*60*24*4));
​ const endDate = new Date(today.getTime() + (1000*60*60*24*5));
​ //const event1 = cal.createAllDayEvent('title',futureDate);
​ //event1.setColor("6");
​ //const event2 = cal.createAllDayEvent('One big event WEEK',today,futureDate);
​ //event2.setDescription('Wow that was a long event');
​ const opts = {
​ location : 'MY HOME',
​ guests : 'education2learning@gmail.com',
​ description : 'The party',
​ sendInvites: true
​ }
​ const event3 = cal.createAllDayEvent('New Party',futureDate,endDate,opts);
​ Logger.log(event3);
​ }

Delete Calendar Events Calendar Event Class Code example

​ function delEvents(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const day = 1000*60*60*24;
​ const endDate = new Date(today.getTime() + (day*365));
​ const events = cal.getEvents(today,endDate);
​ Logger.log(events.length);
​ events.forEach((event)=>{
​ Logger.log(event);
​ event.deleteEvent();
​ })
​ }

Add Remove guests from Event get Guest Details EventGuest Class Code
Example

​ function addMyEvent(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const myDay = 1000*60*60*24*3;
​ const start = new Date(today.getTime() + myDay + (1000*60*60*5));
​ const end = new Date(today.getTime() + myDay + (1000*60*60*8));
​ const event = cal.createEvent('TEST my Event',start,end);
​ event.addGuest('gappscourses+1@gmail.com');
​ event.addGuest('gappscourses+2@gmail.com');
​ event.addGuest('gappscourses+3@gmail.com');
​ }

46

​ function myGuests(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const myDay = 1000*60*60*24*3;
​ const start = new Date(today.getTime() + myDay + (1000*60*60*5));
​ const events = cal.getEventsForDay(start);
​ events.forEach((event)=>{
​ let removeEmail = '';
​ let guests = event.getGuestList();
​ Logger.log(guests);
​ guests.forEach((guest)=>{
​ removeEmail = guest.getEmail();
​ let person = {
​ email : guest.getEmail(),
​ status : guest.getStatus(),
​ gstatus : guest.getGuestStatus(),
​ name:guest.getName(),
​ addGuest:guest.getAdditionalGuests()
​ }
​ Logger.log(person);
​ })
​ event.removeGuest(removeEmail);
​ })
​ //Logger.log(events);
​ }

Code Example for Spreadsheet to list all events in Calendar Mini Project
App

​ function makeaSheet(){
​ const ss = SpreadsheetApp.create('New Cals');
​ const sheet = ss.insertSheet();
​ sheet.setName('cals');
​ sheet.appendRow(['Start Time','End Time','ID','Title','Description']);
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const day = 1000*60*60*24;
​ const end = new Date(today.getTime()+ (day*30));
​ const events = cal.getEvents(today,end);
​ Logger.log(events.length);
​ events.forEach((event)=>{
​ const arr = [];
​ arr.push(event.getStartTime());
​ arr.push(event.getEndTime());
​ arr.push(event.getId());
​ arr.push(event.getTitle());
​ arr.push(event.getDescription());
​ sheet.appendRow(arr);
​ })

​ }
47


​ function addRandomCals(){
​ const cal = CalendarApp.getDefaultCalendar();
​ const today = new Date();
​ const day = 1000*60*60*24;
​ for(let i=0;i<25;i++){
​ const randomDay = Math.floor(Math.random()*30);
​ const start = new Date(today.getTime()+ (randomDay*day));
​ const title = 'My Event #'+i;
​ const event = cal.createAllDayEvent(title,start);
​ }
​ }

Section 8: Google Apps Script Slides Service Class


SlidesApp
Create a new Slide file - open slides by ID source Code example

​ function makeSlides() {
​ const slides = SlidesApp.create('New Name');
​ Logger.log(slides);
​ }

​ function selSlides(){
​ const id = '1Bk1dn81pkgtePNrUVaMGHilN-PIDj7MAzrSGlkrDLt8';
​ const slides = SlidesApp.openById(id);
​ Logger.log(slides.getName());
​ }

Presentation Class - appendSlide add Editor set Slide Background

​ function addaSlide() {
​ const presentSlide = SlidesApp.getActivePresentation();
​ Logger.log(presentSlide);
​ presentSlide.addEditor('education2learning@gmail.com');
​ const layouts = presentSlide.getLayouts();
​ layouts.forEach((layout,index)=>{
​ Logger.log(layout.getLayoutName());
​ Logger.log(index);
​ })
​ const slide = presentSlide.appendSlide(layouts[6]);
​ slide.getBackground().setSolidFill('#00ff00');
​ Logger.log(slide);
​ }
​ function newSlide(){
​ const id = '1Bk1dn81pkgtePNrUVaMGHilN-PIDj7MAzrSGlkrDLt8';
​ const presentSlide = SlidesApp.openById(id);
48

​ const layouts = presentSlide.getLayouts();


​ layouts.forEach((layout,index)=>{
​ Logger.log(layout.getLayoutName());
​ Logger.log(index);
​ })
​ const slide = presentSlide.appendSlide(layouts[6]);
​ slide.getBackground().setSolidFill('#ff0000');
​ Logger.log(slide);
​ }

Update textStyle Background Color Get TextRanges Get Page Elements Get
Slides

​ function updateSlides(){
​ const pres = SlidesApp.getActivePresentation();
​ const slides = pres.getSlides();
​ Logger.log(slides);
​ slides.forEach((slide,index)=>{
​ let myText = `This is slide #${index + 1}`;
​ let val = slide.insertTextBox(myText);
​ Logger.log(val);
​ })
​ }

​ function updateSlidesText(){
​ const pres = SlidesApp.getActivePresentation();
​ const slides = pres.getSlides();
​ //Logger.log(slides);
​ slides.forEach((slide,index)=>{
​ const els = slide.getPageElements();
​ Logger.log(els);
​ els.forEach((el)=>{
​ const val2 = el.asShape();
​ const textRange = val2.getText();
​ textRange.setText('UPDATED #'+index);
​ const textStyle = textRange.getTextStyle();
​ textStyle.setBackgroundColor(ranCol(),ranCol(),ranCol());
​ Logger.log(textRange.getTextStyle());
​ })
​ })
​ }


​ function ranCol(){
​ return Math.floor(Math.random()*255);
​ }

Add UI menu button to duplicate Slide from Current Selection Code


Example
49

​ function onOpen(){
​ const ui = SlidesApp.getUi();
​ ui.createMenu('adv')
​ .addItem('addSlide','addSlide')
​ .addToUi();
​ }

​ function addSlide(){
​ const pres = SlidesApp.getActivePresentation();
​ const curSlide = pres.getSelection();
​ const curPage = curSlide.getCurrentPage();
​ const mySlide = curPage.asSlide();
​ Logger.log(mySlide);
​ const newSlide = mySlide.duplicate();
​ const val1 = newSlide.insertTextBox('NEW ONE');
​ const val2 = mySlide.insertTextBox('OLD ONE');
​ val1.setLeft(200);
​ val2.setLeft(200);
​ Logger.log(newSlide);

​ }

Insert Drive Images with UI button Delete and remove selected Slides
Source Code

​ function onOpen(){
​ const ui = SlidesApp.getUi();
​ ui.createMenu('adv')
​ .addItem('addImage','addImage')
​ .addItem('remove','removeSlide')
​ .addToUi();
​ }

​ function removeSlide(){
​ const slide =
SlidesApp.getActivePresentation().getSelection().getCurrentPage().asSlide();
​ slide.remove();

​ }


​ function addImage(){
​ const slide =
SlidesApp.getActivePresentation().getSelection().getCurrentPage().asSlide();
​ Logger.log(slide)
​ //https://drive.google.com/file/d/13a074ZCrcfpMD_ZqeJWVcCIuWUOI9pUw/view?usp=sharing
​ const id = '13a074ZCrcfpMD_ZqeJWVcCIuWUOI9pUw';
​ const image = DriveApp.getFileById(id);
​ const myImage = slide.insertImage(image);
​ myImage.setLeft(200);
​ myImage.setTop(200);
50

​ myImage.scaleWidth(0.3);
​ myImage.scaleHeight(0.3);
​ myImage.sendToBack();
​ Logger.log(myImage);
​ }

TextRange adding Shapes updating and getting sub ranges of Text Code
Example

​ function onOpen(){
​ const ui = SlidesApp.getUi();
​ ui.createMenu('adv')
​ .addItem('addText','addMytext')
​ .addToUi();
​ }

​ function addMytext(){
​ const slide =
SlidesApp.getActivePresentation().getSelection().getCurrentPage().asSlide();
​ const textShape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX,50,50,200,200);
​ const myShape = slide.insertShape(SlidesApp.ShapeType.SUN,20,20,100,100);
​ Logger.log(myShape);
​ const val1 = myShape.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);
​ val1.sendToBack();
​ const textRange = textShape.getText();
​ Logger.log(textRange);
​ textRange.setText('Hello World');
​ const subRange = textRange.getRange(0,5);
​ Logger.log(subRange);
​ subRange.insertText(3,'MORE TEXT');
​ Logger.log(textRange.asString());
​ }

List layouts Update Master Find text in shapes and remove shapes Source
Code

​ function myLayouts(){
​ const slidePres = SlidesApp.getActivePresentation();
​ const layouts = slidePres.getLayouts();
​ layouts.forEach((layout,index)=>{
​ //Logger.log(layout);
​ const val = layout.getMaster();
​ //const textBox = val.insertTextBox('Layout #'+index);
​ //textBox.setContentAlignment(SlidesApp.ContentAlignment.MIDDLE);
​ //textBox.sendToBack();
​ //textBox.setTitle('text box');
​ const shapes = val.getShapes();
​ shapes.forEach((shape)=>{
​ let shapeText = shape.getText().asString();
​ let boo = shapeText.includes('Layout');
51

​ if(boo){
​ shape.remove();
​ }
​ })
​ Logger.log(textBox);
​ })

Sheets Data to Generate a Slides Presentation Project

​ function slideMaker(){
​ const pres = SlidesApp.create('Slides '+myId());
​ const preID = pres.getId();
​ const folderID = '1tbiAxHrYkxBw-WtHWDFZN7OJxTSUpoAP';
​ const file = DriveApp.getFileById(preID);
​ DriveApp.getFolderById(folderID).addFile(file);
​ const layouts = pres.getLayouts();
​ const data = getDataSheet();
​ data.forEach((row)=>{
​ const newSlide = pres.appendSlide(layouts[0]);
​ const ranBackGround = '#'+Math.random().toString(16).substr(-6);
​ newSlide.getBackground().setSolidFill(ranBackGround,0.3);
​ const pageElements = newSlide.getPageElements();
​ pageElements[0].asShape().getText().setText(row[0]);
​ pageElements[1].asShape().getText().setText(row[1]);
​ })
​ removeFirst(pres);
​ }

​ function testRemove(){
​ const id = '1skgW_ylbacSiXZ1v9IYJUuF2bhwXW7JyJ2tPjcw9WDs';
​ const pres = SlidesApp.openById(id);
​ const slides = pres.getSlides();
​ removeFirst(pres);
​ }

​ function removeFirst(pres){
​ const slides = pres.getSlides();
​ slides[0].remove();
​ Logger.log(slides);

​ }


​ function testData(){
​ const data = getDataSheet();
​ data.forEach((row)=>{
​ Logger.log(row[0]);
​ Logger.log(row[1]);
​ })

​ }

52



​ function selectMyLayout(){
​ const id = '1Bk1dn81pkgtePNrUVaMGHilN-PIDj7MAzrSGlkrDLt8';
​ const layouts = SlidesApp.openById(id).getLayouts();
​ layouts.forEach((layout,index)=>{
​ Logger.log(layout.getLayoutName() , index);
​ })

​ }



​ function getDataSheet(){
​ const id = '1TGUR8UPFabwIw1RkhqTMT4HT_JcaFX2cAwmucByjBRU';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('output');
​ const data = sheet.getDataRange().getValues().slice(1);
​ Logger.log(data);
​ return data;
​ }




​ function myId(){
​ const myDate = new Date().toISOString().slice(0,10);
​ return myDate;
​ }

Slides Service SlidesApp Class options and Methods Source Code

​ function myFunction() {
​ const presentation = SlidesApp.getActivePresentation();
​ Logger.log(presentation)
​ const slide = presentation.appendSlide();
​ Logger.log(slide);
​ const textBox = slide.insertTextBox('My Text');
​ textBox.setContentAlignment(SlidesApp.ContentAlignment.TOP);
​ const pageElements = slide.getPageElements();
​ Logger.log(pageElements);
​ pageElements.forEach((ele)=>{
​ Logger.log(ele);
​ const textRange = ele.asShape().getText().setText('Hello World');
​ Logger.log(textRange);
​ })
​ }
53

Section 9: Google Apps Script Forms Service Class


FormApp
Create a New Form Select Existing Form Add Item Code Example

​ function createaForm() {
​ const form = FormApp.create('MyForm');
​ const item = form.addTextItem();
​ Logger.log(item);
​ Logger.log(form);
​ }

​ function updateMyForm(){
​ const id = '1ssoBcRbLB9x6CFYUR2wbhl-7K5GwnlQl3q2GDCgYJzk';
​ const form = FormApp.openById(id);
​ Logger.log(form);



​ }

Add items to Form Google Form Creation using Apps Script Code Example

​ function updateMyForm(){
​ const id = '1ssoBcRbLB9x6CFYUR2wbhl-7K5GwnlQl3q2GDCgYJzk';
​ const form = FormApp.openById(id);

​ const item1 = form.addCheckboxItem();
​ item1.setChoices([
​ item1.createChoice('First'),
​ item1.createChoice('Second'),
​ item1.createChoice('Three')
​ ]);

​ const item2 = form.addMultipleChoiceItem();
​ item2.setTitle('Do you like Apps Script')
​ .setChoiceValues(['Yes','No','Maybe'])
​ .showOtherOption(true);
​ form.addPageBreakItem().setTitle('thanks');

​ const item3 = form.addGridItem();
​ item3.setTitle('rate your favorite Workspace Service')
​ .setRows(['Sheets','Docs','Forms'])
​ .setColumns(['Top','Average','Bad']);

​ form.addDateItem().setTitle('When did you first start with Apps Script?')

​ Logger.log(form);
​ }
54

Update existing form items with new values make required


code example

​ function myForm(){
​ const id = '1ssoBcRbLB9x6CFYUR2wbhl-7K5GwnlQl3q2GDCgYJzk';
​ const form = FormApp.openById(id);
​ //Logger.log(form.getTitle());
​ //Logger.log(form.getEditUrl());
​ //Logger.log(form.getSummaryUrl());
​ const items = form.getItems();
​ items.forEach((item)=>{
​ Logger.log(item.getType());
​ if(item.getType() =='TEXT'){
​ const textItem =item.asTextItem();
​ textItem.setTitle('NEW Title')
​ .setRequired(true)
​ .setHelpText('Say whatever');
​ }
​ })
​ //Logger.log(items);

​ }

Setting Form to Quiz updating adding Feedback to form choices Code


Example

​ function myFormMaker(){
​ const form = FormApp.create('My Tester 2');
​ form.setIsQuiz(true);
​ const item1 = form.addListItem();
​ item1.setTitle('Do you like Apps Script');
​ item1.setChoices([
​ item1.createChoice('Yes',true),
​ item1.createChoice('No',false),
​ item1.createChoice('Unsure',false)
​ ]);
​ item1.setFeedbackForCorrect(
​ FormApp.createFeedback().setText('Yes').build());
​ item1.setFeedbackForIncorrect(
​ FormApp.createFeedback().setText('Oh No!!!').build()
​ );


55


​ }

Get form response data into Google Script Code Example

​ function myResponses(){
​ const id = '1m1WPu9Jhuq98ubBay7NN0uk9GgQSJILXKqDpill20wo';
​ const form = FormApp.openById(id);
​ //Logger.log(form.getPublishedUrl());
​ const responses = form.getResponses();
​ Logger.log(responses);
​ responses.forEach((res,index)=>{
​ const itemRes = res.getItemResponses();
​ itemRes.forEach((item)=>{
​ Logger.log(item.getItem().getTitle());
​ Logger.log(item.getResponse());
​ })
​ })
​ }

Get form responses add to spreadsheet Project

​ function myResponses(){
​ const id = '1m1WPu9Jhuq98ubBay7NN0uk9GgQSJILXKqDpill20wo';
​ const form = FormApp.openById(id);
​ const responses = form.getResponses();
​ const sheet = makeaSheet();
​ responses.forEach((res,index)=>{
​ const itemRes = res.getItemResponses();
​ itemRes.forEach((item)=>{
​ Logger.log(item.getItem().getTitle());
​ Logger.log(item.getResponse());
​ sheet.appendRow([item.getItem().getTitle(),item.getResponse()]);
​ })
​ })
​ }

​ function makeaSheet(){
​ const ss = SpreadsheetApp.create('Form data');
​ const sheet = ss.insertSheet();
​ sheet.setName('Form Data');
​ sheet.appendRow(['Question','Response']);
​ return sheet;
​ }

How to Create a Math Quiz in Google Forms Apps Script Quiz Generator
Project

​ function makeQuiz(){
​ const form = FormApp.create('Quiz 1');
56

​ form.setIsQuiz(true);
​ for(let i=0;i<10;i++){
​ let val1 = randomNum(1,50);
​ let val2 = randomNum(1,50);
​ let ans = String(val1 + val2);
​ const item = form.addListItem();
​ const title = `${val1}+${val2}=`;
​ item.setTitle(title);
​ const myArr = [];
​ let boo = false;
​ for(let x=0;x<3;x++){
​ let temp = String(randomNum(1,50));
​ if((randomNum(1,30) < 10) && !boo){
​ myArr.push(item.createChoice(ans,true));
​ boo = true;
​ }
​ if(ans != temp){
​ myArr.push(item.createChoice(temp,false));
​ };
​ }
​ if(!boo){
​ myArr.push(item.createChoice(ans,true));
​ }
​ item.setChoices(myArr);
​ item.setFeedbackForCorrect(FormApp.createFeedback().setText(ans).build())
​ }
​ }


​ function randomNum(min,max){
​ min = Math.ceil(min);
​ max = Math.floor(max);
​ return Math.floor(Math.random()*(max-min+1)+min);
​ }

Set Progressbar shuffle questions add Scale Item Examples

​ function tester(){
​ const form = FormApp.create('new one');
​ form.setShuffleQuestions(true);
​ form.setProgressBar(true);
​ const item = form.addScaleItem();
​ item.setTitle('pick a number');
​ item.setBounds(1,10);

​ }
57

Section 10: Google Workspace services


Contact Service Add Contact Get and update Contact Info ContactApp
Class

​ function listContacts(){
​ const contacts = ContactsApp.getContacts();
​ Logger.log(contacts);
​ contacts.forEach((contact)=>{
​ const person = contact.getPrimaryEmail();
​ if(person == 'tester@gmail.com'){
​ Logger.log(contact.getPrimaryEmail());
​ contact.setFullName('Laurence Tester');
​ contact.setNickname('test Account');
​ }
​ })
​ }

​ function addPerson(){
​ const contact = ContactsApp.createContact('Test','Account','tester@gmail.com');
​ Logger.log(contact);

​ }

Language App Translate text to different Languages Code Example

​ function updateText() {
​ const id = '19gio49trkgsiehrBcfHQkJhWJqXd-r8pGmyPgIahJgo';
​ const sheet = SpreadsheetApp.openById(id).getSheets()[0];
​ Logger.log(sheet.getName());
​ const data = sheet.getDataRange().getValues();
​ Logger.log(data);
​ data.forEach((str,index)=>{
​ const newStr = LanguageApp.translate(str,'en','es');
​ Logger.log(newStr);
​ const range = sheet.getRange((index+1),2);
​ range.setValue(newStr);
​ })
​ }

Example of Maps Service - Add Map to Google Doc Coding Example

​ function findMe() {
​ const mapFinder = Maps.newGeocoder().setBounds(40.699642, -74.021072, 40.877569,
-73.908548).geocode('Main st');
​ Logger.log(mapFinder);
​ const results = mapFinder.results;
​ Logger.log(results);
​ const doc = DocumentApp.create('New Map 2');
58

​ const body = doc.getBody();


​ const map = Maps.newStaticMap();
​ for(let i=0;i<results.length;i++){
​ const result = results[i];
​ map.setMarkerStyle(null,null,i+1);
​ map.addMarker(result.geometry.location.lat,result.geometry.location.lng);
​ body.appendListItem(result.formatted_address)
​ }
​ const img = Utilities.newBlob(map.getMapImage(),'image/png');
​ body.appendImage(img);


​ }

https://developers.google.com/maps/coverage

Get User Info Send Log to Email Create a Doc from Log details Code
Examples

​ function test1() {
​ const user = Session.getActiveUser();
​ Logger.log(user.getEmail());
​ }

​ function test2(){
​ const val1 = 'Hello';
​ const val2 = 'World';
​ Logger.log('This is the message %s %s',val1,val2);
​ }

​ function test3(){
​ const val1 = 'Hello';
​ const val2 = 'World';
​ Logger.log('This is the message %s %s',val1,val2);
​ const val = Logger.getLog();
​ const doc = DocumentApp.create('my Log');
​ const body = doc.getBody();
​ body.appendParagraph(val);
​ }

​ function test4(){
​ const userEmail = Session.getActiveUser().getEmail();
​ Logger.log(userEmail);
​ const val1 = 'Hello';
​ const val2 = 'World';
​ Logger.log('This is the message %s %s',val1,val2);
​ const val = Logger.getLog();
​ MailApp.sendEmail(userEmail,'my log',val);
​ }

59

output content using ContentService Set file as Download from URL Code
Example

​ function doGet(){
​ const myOutput = 'Hello World 2';
​ //return ContentService.createTextOutput(myOutput);
​ return ContentService.createTextOutput(myOutput).downloadAsFile('test.txt');

​ }

HTMLservice out to send data client side to server side

​ function doGet(){
​ const html = HtmlService.createTemplateFromFile('temp');
​ html.test = 'HELLO WORLD';
​ return html.evaluate();
​ }

​ function test1(){
​ const temp = '<h1>Hello World 2</h1><?= new Date() ?>';
​ const html = HtmlService.createTemplate(temp);
​ Logger.log(html.evaluate().getContent());

​ }

​ function doGet1(){
​ const temp = '<h1>Hello World 2</h1><?= new Date() ?>';
​ const html = HtmlService.createTemplate(temp);
​ return html.evaluate();
​ }

​ function doGet2(){
​ const html = '<h1>Hello World 2</h1>';
​ return HtmlService.createHtmlOutput(html);
​ }

​ function doGet3(){
​ const html = HtmlService.createHtmlOutputFromFile('index');
​ Logger.log(html);
​ return html;
​ }

​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <h1>Hello</h1>
​ <p><?= new Date()?></p>
60

​ <p><?= test ?></p>


​ </body>
​ </html>
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <style>
​ body {
​ background:red;
​ }
​ </style>
​ </head>
​ <body>
​ <h1>Hello</h1>
​ <p>Thank you for visiting</p>
​ </body>
​ </html>

Spreadsheet Data to Client Side - Get e Parameters send to Client Side


output

​ function doGet(e){
​ const html = HtmlService.createTemplateFromFile('para');
​ let allowed = 0;
​ if('id' in e.parameters){
​ allowed = e.parameters['id'][0];
​ }

​ html.data = allowed;
​ return html.evaluate();


​ }



​ function doGet1(){
​ const id = '19gio49trkgsiehrBcfHQkJhWJqXd-r8pGmyPgIahJgo';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('Sheet1');
​ const data = sheet.getDataRange().getValues();
​ Logger.log(data);
​ const html = HtmlService.createTemplateFromFile('output');
​ html.data = data;
​ return html.evaluate();
​ }
​ <script>
​ const datags = <?!= JSON.stringify(data) ?>;
​ console.log(datags);

61

​ </script>
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <div class="output"></div>
​ <script>
​ const output = document.querySelector('.output');
​ console.log(output);
​ output.textContent = datags;
​ </script>
​ </body>
​ </html>

Project Server Side Input content to Spreadsheet Data client to server


Examples

​ function doGet(){
​ const html = HtmlService.createTemplateFromFile('data');
​ return html.evaluate();
​ }

​ function testMessage(message){
​ Logger.log(message);
​ const id = '19gio49trkgsiehrBcfHQkJhWJqXd-r8pGmyPgIahJgo';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('message');
​ sheet.appendRow([message]);
​ return {'response':true,'message':message};

​ }
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <div class="output"></div>
​ <input type='text' name='message' placeholder="your message" value='testing' >
​ <button>Send Data</button>
​ <script>
​ const output = document.querySelector('.output');
​ const message = document.querySelector('input');
​ const btn = document.querySelector('button');

​ btn.addEventListener('click',(e)=>{
​ console.log(message.value);
​ google.script.run.withSuccessHandler(onSuccess).testMessage(message.value);
​ })

62


​ function onSuccess(rep){
​ console.log(rep);
​ }
​ console.log(output);

​ </script>
​ </body>
​ </html>

Store values in storage store within documents scripts and users Code
Examples

​ function pDoc() {
​ const docProp = PropertiesService.getDocumentProperties();
​ docProp.setProperty('myKey3','myValue4');
​ Logger.log(docProp.getProperties());
​ const props = docProp.getProperties();
​ Logger.log(props['myKey2']);
​ docProp.deleteProperty('myKey3');
​ Logger.log(docProp.getProperties());
​ }
​ function pUsr(){
​ const docProp = PropertiesService.getUserProperties();
​ docProp.setProperty('myKey5','myValue4');
​ Logger.log(docProp.getProperties());
​ const props = docProp.getProperties();
​ Logger.log(props['myKey2']);
​ docProp.deleteProperty('myKey3');
​ Logger.log(docProp.getProperties());

​ }

​ function pSci() {
​ const docProp = PropertiesService.getScriptProperties();
​ docProp.setProperty('myKey2','myValue4');
​ Logger.log(docProp.getProperties());
​ const props = docProp.getProperties();
​ Logger.log(props['myKey2']);
​ docProp.deleteProperty('myKey3');
​ Logger.log(docProp.getProperties());
​ }

Connect to web data API use data within script reproduce Google siteb in
WebApp

​ function getWebsite(){
​ const url = 'http://www.google.com/';
​ const rep = UrlFetchApp.fetch(url);
​ Logger.log(rep.getContentText());
63

​ }

​ function getData(){
​ const url = 'https://randomuser.me/api/?results=5';
​ const rep = UrlFetchApp.fetch(url);
​ const results = JSON.parse(rep);
​ const id = '19gio49trkgsiehrBcfHQkJhWJqXd-r8pGmyPgIahJgo';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('people');
​ //Logger.log(results.results);
​ const fileName = DriveApp.createFile('people.json',rep);
​ results.results.forEach((person)=>{
​ Logger.log(person.name);
​ sheet.appendRow([person.name.title,person.name.first,person.name.last]);
​ })

​ }


​ function doGet(){
​ const url = 'http://www.google.com/';
​ const rep = UrlFetchApp.fetch(url);
​ const html = rep.getContentText();
​ return HtmlService.createHtmlOutput(html);

​ }

Section 11: Google Apps Script Common


Create Spreadsheet populate data - Add a Chart to the Sheet from the data
Code

​ function makeSheet(){
​ const ss = SpreadsheetApp.create('testSheet1');
​ const sheet = ss.insertSheet('chart');
​ sheet.appendRow(['Date','Team A','Team B']);
​ const today = new Date();
​ const day = 1000*60*60*24;

​ for(let i=0;i<20;i++){
​ const datePlayed = new Date(today.getTime() + (100*day)+(i*3*day));
​ const score1 = Math.floor(Math.random()*20);
​ const score2 = Math.floor(Math.random()*20);
​ sheet.appendRow([datePlayed,score1,score2]);
​ }

​ const remover = ss.getSheetByName('sheet1');
​ ss.deleteSheet(remover);
​ Logger.log(ss.getId());
64

​ }

​ function makeChart(){
​ const id = '1y1CLO0EqDirKpWBxzqDhAoL-GhudGp0M73Lr9ollGFU';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheetByName('chart');
​ Logger.log(ss);
​ const range = sheet.getDataRange();
​ const hAxis = {
​ gridlines: {count:10}
​ }
​ const temp = sheet.newChart().asLineChart();
​ const chart = temp
​ .addRange(range)
​ .setPosition(3,5,0,0)
​ .setNumHeaders(1)
​ .setOption('hAxis',hAxis)
​ .build();

​ sheet.insertChart(chart);
​ }

Create Slides Presentations from Charts in Spreadsheet Code Example

​ function slideMakers(){
​ const id = '1y1CLO0EqDirKpWBxzqDhAoL-GhudGp0M73Lr9ollGFU';
​ const ss = SpreadsheetApp.openById(id);
​ const sheet = ss.getSheetByName('chart');
​ const charts = sheet.getCharts();
​ Logger.log(charts);
​ const slides = SlidesApp.create(sheet.getName());
​ const els = slides.getSlides()[0].getPageElements();
​ els.forEach((el)=>{
​ el.remove();
​ })
​ slides.getSlides()[0].insertTextBox('Welcome to the Charts');
​ charts.forEach((chart)=>{
​ const newSlide = slides.appendSlide();
​ newSlide.insertSheetsChart(chart,20,10,600,400);
​ })
​ }

Generate PDF from file send as attachment in email PDF file maker Code
example

​ function makeaPDF(){
​ const id = '1y1CLO0EqDirKpWBxzqDhAoL-GhudGp0M73Lr9ollGFU';
​ const oldFile = DriveApp.getFileById(id);
​ Logger.log(oldFile.getName());
​ const blob = oldFile.getBlob();
65

​ const file = DriveApp.createFile(blob);//create from blob


​ file.setName('Slides Tester');
​ const pdf = file.getAs('application/pdf');
​ const file2 = DriveApp.createFile(pdf);
​ file2.setName('As PDF');
​ const email = Session.getActiveUser().getEmail();
​ MailApp.sendEmail(email,'PDF attached','',{
​ attachments: [file.getAs('application/pdf')],
​ name:'Attach PDF'
​ })


​ }

Docs UI menu and Event Object onOpen simple trigger Code Examples

​ function onOpen(e){
​ const ui = DocumentApp.getUi();
​ ui.createAddonMenu()
​ .addItem('fun 1','fun1')
​ .addItem('fun 2','fun2')
​ .addToUi();

​ ui.createMenu('Custom Menu')
​ .addItem('fun 1','fun1')
​ .addItem('fun 2','fun2')
​ .addToUi();

​ //const doc = DocumentApp.getActiveDocument();
​ //const newContent = String(new Date());
​ //Logger.log(e);
​ //const eventDetails = JSON.stringify(e);
​ //doc.getBody().appendParagraph(eventDetails);


​ }

​ function fun1(){
​ const doc = DocumentApp.getActiveDocument().getBody();
​ const txt = doc.editAsText();
​ txt.insertText(10,'New Text \n New Line \n');
​ }

​ function fun2(){
​ const doc = DocumentApp.getActiveDocument().getBody();
​ const para = doc.appendParagraph('New Paragraph');
​ }

Code examples Google Sheets UI menu Sheet onEdit and


onSelectionChange Code
66

​ function onEdit(e) {
​ logger(JSON.stringify(e));
​ const range = e.range;
​ range.setNote('Updated '+new Date());
​ logger(range.getLastRow());
​ range.setBackground('#00ff00');
​ }

​ function onSelectionChange(e) {
​ const range = e.range;

logger2(['Selection',JSON.stringify(e),range.getNumRows(),range.getNumColumns(),range.g
etFontSize(),JSON.stringify(range.getBackgrounds())]);
​ let total = range.getNumRows() + range.getNumColumns();
​ if(total > 8){
​ range.setBackground('#ee00ff');
​ }else{
​ range.setBackground('#00cc22');
​ }

​ }



​ function onOpen(e) {
​ //const ss = SpreadsheetApp.getActiveSpreadsheet();
​ //const menuItems = [{name:'Fun 1',functionName:'fun1'}];
​ ///ss.addMenu('adv',menuItems);
​ //ui.createAddonMenu()
​ logger(JSON.stringify(e));

​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('NEW')
​ .addItem('fun 1','fun1')
​ .addToUi();
​ }
​ function logger2(val){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('logger');
​ ss.appendRow(val);

​ }
​ function logger(val){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('logger');
​ ss.appendRow([val]);

​ }
​ function fun1(){
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
​ ss.appendRow(['NEW','Cols']);

​ }
67

doGet method create a simple webapp return event object details of


webapp

​ function doGet(e) {
​ //const html = JSON.stringify(e);
​ const html = '<h1>Hello World</h1>'
​ return HtmlService.createHtmlOutput(html);
​ }

Using Code to Setup Application Triggers Automate your Apps Script Code
Examples

​ function fun1(){
​ const id = '1DbghUBYtBoXeR3B7i3iFVUjkpmEIKWUJnHk7LG6Wi0o';
​ const doc = DocumentApp.openById(id).getBody();
​ const val = String(new Date());
​ Logger.log(doc);
​ doc.appendParagraph(val);
​ }
​ function fun2(){
​ const id = '1DbghUBYtBoXeR3B7i3iFVUjkpmEIKWUJnHk7LG6Wi0o';
​ const doc = DocumentApp.openById(id).getBody();
​ const val = 'Hello World';
​ doc.appendParagraph(val);
​ doc.appendHorizontalRule();
​ }

​ function addTrigger(){
​ ScriptApp.newTrigger('fun2')
​ .timeBased()
​ .everyMinutes(1)
​ .create();


​ }


​ function updateTriggers(){
​ const allTriggers = ScriptApp.getProjectTriggers();
​ Logger.log(allTriggers);
​ allTriggers.forEach((tri)=>{
​ Logger.log(tri.getUniqueId());
​ Logger.log(tri.getEventType());
​ Logger.log(tri.getHandlerFunction());
​ if(tri.getHandlerFunction() == 'fun2'){
​ ScriptApp.deleteTrigger(tri);
​ }
​ })

68

​ }

https://developers.google.com/apps-script/guides/services/quotas - get
quotas

Section 12: Mini Projects with Web Apps Create web


app URLs using Google
MultiPage WebApp with Dynamic Menu and Include Files Code Example

​ function doGet(e) {
​ let temp = 'index';
​ if ('page' in e.parameters) {
​ temp = e.parameters['page'][0]
​ }
​ try {
​ const html = HtmlService.createTemplateFromFile(temp);
​ html.data = { title: temp, e: e }
​ return html.evaluate();
​ }
​ catch (err) {
​ const html = HtmlService.createHtmlOutput('Page not found 404 Error:' +
JSON.stringify(err));
​ return html;
​ }
​ }

​ function getScriptUrl() {
​ const url = ScriptApp.getService().getUrl();
​ return url;
​ }




​ function menu() {
​ const url = getScriptUrl();
​ let html = HtmlService.createHtmlOutputFromFile('menu').getContent();
​ html = html.replace(/\?page/g, url + '?page');
​ Logger.log(html);
​ return html;
​ }

​ function tester() {
​ const filename = 'index';
​ Logger.log(HtmlService.createHtmlOutputFromFile(filename));
​ Logger.log(HtmlService.createHtmlOutputFromFile(filename).getContent());
69

​ }

​ function include(filename) {
​ return HtmlService.createHtmlOutputFromFile(filename).getContent();
​ }
​ <script>
​ const datags = <?!= JSON.stringify(data) ?>;
​ console.log(datags);
​ //document.write(JSON.stringify(datags));
​ </script>
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <?!= include('style1') ?>
​ </head>
​ <body>
​ <h1>Hello this is page index</h1>
​ <?!= menu() ?>
​ <?!= include('randomWords') ?>
​ <?!= include('random2') ?>
​ </body>
​ </html>
​ <script>
​ function randomWords(){
​ let h1 = document.createElement('h1');
​ let title = datags.title.toUpperCase();
​ h1.textContent = `${title} Is this current page`;
​ document.body.append(h1);
​ let output = document.createElement('div');
​ document.body.append(output);
​ for(let i = 0;i<100;i++){
​ let val = Math.floor(Math.random()*8)+1;
​ output.innerHTML += Math.random().toString(36).substr(2,val) + ' ';
​ }
​ }

​ </script>
​ <style>
​ body {
​ background:#eee;
​ color:#111;
​ }
​ ul{
​ list-style-type:none;
​ margin:0;
​ padding:0;
​ overflow:hidden;
​ }
​ li {
​ float:left;
​ }
​ li a{
70

​ display:block;
​ padding:5px;
​ background-color:#ccc;

​ }
​ </style>
​ <script>
​ for(let x=0;x<3;x++){
​ randomWords();
​ }
​ </script>
​ <div >
​ <ul style="background:red">
​ <li><a href="?page=index" target="_top">Home Page</a></li>
​ <li><a href="?page=index2" target="_top">Index 2</a></li>
​ <li><a href="?page=index3" target="_top">Index 3</a></li>
​ <li><a href="?page=index4" target="_top">Index 4</a></li>

​ </ul>
​ </div>
​ <hr>

Dynamic Interactions Menu Options with Docs Send data receive from
client side

​ function onOpen(){
​ const ui = DocumentApp.getUi();
​ ui.createMenu('ADV')
​ .addItem('sideBar','mysidebar')
​ .addItem('dialog','mydialog')
​ .addToUi();
​ }

​ function mysidebar(){
​ const html = HtmlService.createTemplateFromFile('side').evaluate();
​ html.setTitle('Doc Updater');
​ DocumentApp.getUi().showSidebar(html);
​ }

​ function mydialog(){
​ const html = HtmlService.createTemplateFromFile('dialog').evaluate();
​ html.setWidth(600).setHeight(400);
​ DocumentApp.getUi().showModelessDialog(html,'Dialog');

​ }
​ function removeEle(val){
​ const body = DocumentApp.getActiveDocument().getBody();
​ const paras = body.getParagraphs();
​ paras[val].setText('REMOVE');
​ }

71

​ function listEles(){
​ const body = DocumentApp.getActiveDocument().getBody();
​ Logger.log(body.getParagraphs());
​ const holder = [];
​ const paras = body.getParagraphs();
​ paras.forEach((p,index)=>{
​ const obj = {
​ type:p.getType(),
​ content:p.getText(),
​ index : index
​ }
​ holder.push(obj);
​ })
​ Logger.log(holder);
​ return holder;
​ }


​ function addtoDoc(data){
​ const body = DocumentApp.getActiveDocument().getBody();
​ const h = data.h1;
​ const p = data.p;
​ const header = body.appendParagraph(h);
​ const style = {};
​ style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING1;
​ header.setAttributes(style);
​ const contentPara = body.appendParagraph(p);
​ const style1 = {};
​ style1[DocumentApp.Attribute.BACKGROUND_COLOR] = '#00ff00';
​ contentPara.setAttributes(style1);
​ return {success:true};
​ }


​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <style>
​ input, textarea, label{
​ display:block;
​ }
​ body{
​ color:white;
​ background:#ddd;
​ }

​ </style>
​ </head>
​ <body>
​ <h1>Content Adder</h1>
​ <div >
​ <label for="heading">Add Heading</label>
72

​ <input id="heading" type="text" value="heading">


​ </div>
​ <div >
​ <label for="para">Add Heading</label>
​ <textarea id="para" ></textarea>
​ </div>
​ <div>
​ <button class="adder">Save to Doc</button>
​ </div>

​ <?!= HtmlService.createHtmlOutputFromFile('sidejs').getContent() ?>

​ </body>
​ </html>







​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <div class="output"></div>
​ <div>
​ <button class="adder">List page elements</button>
​ </div>

​ <?!= HtmlService.createHtmlOutputFromFile('dialogjs').getContent() ?>
​ </body>
​ </html>

​ <script>
​ const btn = document.querySelector('.adder');
​ const contentHeader =document.querySelector('#heading');
​ const contentParagraph =document.querySelector('#para');
​ console.log(contentParagraph);
​ console.log(contentHeader);
​ btn.addEventListener('click',()=>{
​ const obj = {
​ 'h1' : contentHeader.value,
​ 'p' : contentParagraph.value
​ }
​ google.script.run.withSuccessHandler(success).addtoDoc(obj);

​ console.log('clicked');
​ })
​ function success(data){
​ console.log(data);
73

​ }
​ </script>

​ <script>
​ const btn = document.querySelector('.adder');
​ const output =document.querySelector('.output');

​ btn.addEventListener('click',loadList);

​ function loadList(){
​ google.script.run.withSuccessHandler(success).listEles();
​ console.log('clicked');
​ }
​ function success(data){
​ console.log(data);
​ output.innerHTML = '';
​ data.forEach((el)=>{
​ console.log(el);
​ if(el.content.length > 0){
​ let div = document.createElement('div');
​ div.textContent = el.content;
​ div.addEventListener('click',(e)=>{
​ console.log(el.index);
​ google.script.run.withSuccessHandler(loadList).removeEle(el.index);
​ })
​ output.append(div);
​ }
​ })
​ }
​ </script>

Custom Dynamic Quiz WebApp with Sheets Data and Results Code
Example

​ function doGet(e) {
​ let email = Session.getActiveUser().getEmail();
​ try {
​ const html = HtmlService.createTemplateFromFile('quiz');
​ html.data = {
​ data: quizData(),
​ email: email
​ }
​ return html.evaluate();
​ }
​ catch (e) {
​ return HtmlService.createHtmlOutput('<h1>Not found</h1>');
​ }

​ }

74

​ function quizData() {
​ const id = '1IFBVT-uvXcHJTZIr4ENMlGZFvuHM6hBkisEyrbHAXvg';
​ const data =
SpreadsheetApp.openById(id).getSheetByName('questions').getDataRange().getValues();
​ const headings = data[0];
​ const questions = data.slice(1);
​ const ques = [];
​ questions.forEach((el) => {
​ let obj = {};
​ headings.forEach((header, index) => {
​ obj[header.toLowerCase()] = el[index];
​ })
​ ques.push(obj);
​ })
​ return ques;
​ }



​ function addSheet(vals) {
​ const id = '1IFBVT-uvXcHJTZIr4ENMlGZFvuHM6hBkisEyrbHAXvg';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('results');
​ const headings = sheet.getDataRange().getValues()[0];
​ const holder = [];
​ for (x in headings) {
​ let output = (headings[x] in vals) ? vals[headings[x]] : '';
​ if (headings[x] == 'date') {
​ output = new Date();
​ }
​ holder.push(output);
​ }
​ sheet.appendRow(holder);
​ let lastRow = sheet.getLastRow();
​ return { obj: vals, headings: headings, row: lastRow };
​ }
​ <script>
​ const data = <?!= JSON.stringify(data) ?>;
​ console.log(data);

​ </script>


​ <!DOCTYPE html>
​ <html>

​ <head>
​ <base target="_top">
​ <style>
​ .ques {
​ font-size: 1.5em;
​ color: black;
​ font-family: arial;

75


​ }

​ .box {
​ padding: 10px;
​ border: 1px solid black;
​ margin: 5px;

​ }

​ label {
​ font-size: 0.7em;
​ color: #ddd;
​ padding: 2px;
​ }

​ .guideWord {
​ font-size: 0.9em;
​ padding: 10px;
​ color: #333;
​ }

​ button {
​ display: block;
​ width: 100%;
​ padding: 10px;
​ border-radius: 15px;
​ border: 1px solid black;
​ }

​ .userInfo {
​ width: 100%;
​ text-align: center;
​ background: black;
​ }

​ .userInfo input {
​ width: 70%;
​ }
​ </style>
​ </head>

​ <body>
​ <form class="questions">
​ <div class="userInfo">
​ <label for="email">Your Email</label>
​ <input type="email" id="email" name="email">
​ </div>
​ <div class="userInfo">
​ <label for="name">Your Name</label>
​ <input type="text" id="name" name="name" value="Laurence">
​ </div>
​ </form>
76

​ <?!= HtmlService.createHtmlOutputFromFile('quizjs').getContent() ?>


​ </body>

​ </html>
​ <script>
​ console.log('ready');
​ console.log(data.data);
​ data.data.sort(()=> .5 - Math.random());
​ console.log(data.data);
​ const questions = document.querySelector('.questions');
​ const myEmail = document.querySelector('#email');
​ const listQ = document.createElement('div');
​ const btn = document.createElement('button');
​ btn.textContent = 'Submit Quiz';
​ btn.setAttribute('type','submit');
​ questions.addEventListener('submit',subForm);
​ questions.append(listQ);
​ myEmail.value = data.email;
​ console.log(questions);
​ data.data.forEach((el)=>{
​ const li = document.createElement('div');
​ li.classList.add('box');
​ listQ.append(li);
​ genInput(el,li);
​ console.log(el);
​ })
​ questions.append(btn);


​ function genInput(el,li){
​ const mc = document.createElement('div');
​ li.append(mc);
​ const div1 = document.createElement('div');
​ div1.textContent = el.question;
​ div1.classList.add('ques');
​ mc.append(div1);
​ const div2 = document.createElement('div');
​ mc.append(div2);
​ const span1 = document.createElement('span');
​ div2.append(span1);
​ span1.classList.add('guideWord');
​ span1.textContent = 'Worst';
​ for( let i=1;i<6;i++){
​ const span = document.createElement('span');
​ const input = document.createElement('input');
​ if(i==1){
​ input.required = true;
​ //input.checked = true;
​ }
​ input.setAttribute('type','radio');
​ input.setAttribute('name',el.id);
​ input.setAttribute('value',i);
​ input.setAttribute('id',el.id+i);
77

​ div2.append(input);
​ const label = document.createElement('label');
​ label.setAttribute('for',el.id+i);
​ label.textContent = i;
​ div2.append(label);
​ }
​ const span2 = document.createElement('span');
​ div2.append(span2);
​ span2.classList.add('guideWord');
​ span2.textContent = 'Best';
​ }

​ function subForm(e){
​ e.preventDefault();
​ console.log('submit me');
​ const res = {};
​ res['name'] = document.querySelector('input[name="name"]').value;
​ res['email'] = document.querySelector('input[name="email"]').value;
​ const vals = questions.querySelectorAll('input:checked');
​ console.log(vals);
​ vals.forEach((i,index)=>{
​ res[i.name] = Number(i.value);
​ })
​ btn.disabled = true;
​ btn.style.backgroundColor = 'red';
​ btn.textContent = 'Saving......';
​ google.script.run.withSuccessHandler(onSuccess).addSheet(res);
​ console.log(res);
​ }
​ function onSuccess(e){
​ console.log(e);
​ questions.innerHTML = `Thank you for submiting your results.
​ Your results are in row ${e.row}`;

​ }
​ </script>

Section 13: Create a WebApp API endpoint Google


Apps Script Addon Project
Create API endpoint with Sheets Data - Connect using JavaScript Fetch
methods

​ function doGet() {
​ const data = {
​ status :'success',
​ quotes : myData()
​ }
​ const output = JSON.stringify(data);
78

​ return
ContentService.createTextOutput(output).setMimeType(ContentService.MimeType.JSON);
​ }

​ function myData(){
​ const id ='1JixK8u48QiCVY1Ozyd9Tt_eiISmQ_TFCWo6wjlV-msw';
​ const sheet = SpreadsheetApp.openById(id).getSheetByName('posts');
​ const rows = sheet.getDataRange().getValues();
​ const quotes = rows.slice(1);
​ return quotes;
​ }

​ const output = document.querySelector('div');
​ const url = 'https://script.google.com/macros/s/*****-/exec';
​ fetch(url).then(rep => rep.json()).then((data)=>{
​ console.log(data);
​ data.quotes.forEach((el)=>{
​ output.innerHTML += el[1] + '<br> ';
​ })
​ })

appscript json manifest examples for Google Apps Script Addon

​ {
​ "timeZone": "America/New_York",
​ "dependencies": {},
​ "exceptionLogging": "STACKDRIVER",
​ "oauthScopes": [
​ "https://www.googleapis.com/auth/documents.currentonly",
​ "https://www.googleapis.com/auth/documents"
​ ],
​ "runtimeVersion": "V8",
​ "addOns": {
​ "common": {
​ "name": "Quotes",
​ "logoUrl": "https://discoveryvip.com/mathGame.png",
​ "layoutProperties": {
​ "primaryColor": "#2772ed"
​ },
​ "homepageTrigger": {
​ "runFunction": "onHomepage"
​ }
​ },
​ "docs": {}
​ }
​ }

Code Example Google Apps Script Addon Docs Addon adding quotes to
Docs
79

​ function onHomepage(e) {
​ return createSel(e);
​ }

​ function createSel(e) {
​ const hostApp = e['hostApp'];
​ const builder = CardService.newCardBuilder();
​ builder.addSection(CardService.newCardSection()
​ .addWidget(CardService.newButtonSet()
​ .addButton(CardService.newTextButton()
​ .setText('Add Quote')
​ .setOnClickAction(CardService.newAction().setFunctionName('addQuote'))
​ .setDisabled(false)
​ )
​ )
​ )
​ return builder.build();
​ }


​ function getQuotes() {
​ const url = 'https://script.google.com/macros/s/********hSieWqRKG_-/exec';
​ const rep = UrlFetchApp.fetch(url);
​ const myObj = JSON.parse(rep);
​ Logger.log(myObj);
​ Logger.log(myObj.quotes);
​ const val = Math.floor(Math.random() * myObj.quotes.length);
​ Logger.log(myObj.quotes[val]);
​ return myObj.quotes[val]
​ }






​ function addQuote() {
​ const doc = DocumentApp.getActiveDocument();
​ const body = doc.getBody();
​ const cursor = doc.getCursor();
​ const quoteData = getQuotes();
​ if (cursor) {
​ cursor.insertText(quoteData[1] + '\n ' + quoteData[0]);
​ } else {
​ const style = {};
​ style[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.HEADING1;
​ const para1 = body.appendParagraph(quoteData[1]); //quote
​ para1.setAttributes(style);
​ const style1 = {};
​ style1[DocumentApp.Attribute.HEADING] = DocumentApp.ParagraphHeading.NORMAL;
​ const para2 = body.appendParagraph(quoteData[0]); //author
​ para2.setAttributes(style1);
​ }
80


​ }

Section 14: Apps Script Code Examples Questions


and Sample Code
Code Example Apps Script Add table rows sample code

​ function adder(){
​ const body = DocumentApp.getActiveDocument().getBody();
​ const tables = body.getTables();
​ const cells = ["A","B","C","D","E"];
​ tables[1].insertTableRow(1).appendTableCell('INSERTed');
​ tables[2].removeRow(2);
​ tables.forEach((table)=>{
​ //const tableRow = table.appendTableRow();
​ const tableRow = table.insertTableRow(2);
​ cells.forEach((cell)=>{
​ tableRow.appendTableCell('2' + cell);
​ })

​ })
​ }

​ function tableData(){
​ const tables = DocumentApp.getActiveDocument().getBody().getTables();
​ tables.forEach((table,index)=>{
​ let temp = table.getRow(index);
​ Logger.log(temp);
​ Logger.log(temp.getText());
​ })
​ }

​ function maker(){
​ const body = DocumentApp.getActiveDocument().getBody();
​ const cells = ["A","B","C","D","E"];
​ body.appendTable([cells]);
​ }

​ function makeTable() {
​ const doc = DocumentApp.getActiveDocument();
​ const body = doc.getBody();
​ Logger.log(body);
​ const arr = [];
​ for(let x=0;x<4;x++){
​ const row = [];
​ for(let y=0;y<5;y++){
​ row.push(x + '-' + y);
81

​ }
​ arr.push(row);
​ Logger.log(row);
​ }
​ body.appendTable(arr);
​ Logger.log(arr);
​ }

Source Coding Example Doc element Copy to new target Doc body

​ function copyDocContent() {
​ const srcID = '1******y6d5qDUM';
​ const tarID = '1N********E9xxLbJ1g';
​ const srcDoc = DocumentApp.openById(srcID);
​ const tarDoc = DocumentApp.openById(tarID);
​ const tBody = tarDoc.getBody();
​ tBody.clear();
​ tBody.appendParagraph('Last Updated ').appendHorizontalRule();
​ const sBody = srcDoc.getBody();
​ Logger.log(sBody.editAsText().getText());
​ Logger.log(sBody.getNumChildren());
​ for(let i=0;i<sBody.getNumChildren();i++){
​ Logger.log(sBody.getChild(i));
​ const el = sBody.getChild(i);
​ if(el.getType()=='PARAGRAPH'){
​ const newEl = el.copy();
​ Logger.log(newEl);
​ tBody.appendParagraph(newEl);
​ };
​ if(el.getType()=='LIST_ITEM'){
​ const newEl = el.copy();
​ const list1 = tBody.appendListItem(newEl);
​ list1.setGlyphType(DocumentApp.GlyphType.SQUARE_BULLET);
​ };
​ if(el.getType()=='TABLE'){
​ const newEl = el.copy();
​ tBody.appendTable(newEl);
​ };
​ }

​ }

Source Code How to Send Emails from Google Sheets using HTML as
Template

Apps Script

​ function onOpen() {
​ const ui = SpreadsheetApp.getUi();
​ ui.createMenu('send email').addItem('Approve', 'approver').addToUi()
82

​ }

​ function approver() {
​ const ui = SpreadsheetApp.getUi();
​ const row = SpreadsheetApp.getActiveSheet().getActiveCell().getRow();
​ Logger.log(row);
​ const data = SpreadsheetApp.getActiveSheet().getRange(row, 1, 1, 3).getValues()[0];
​ const user = {
​ first: data[0]
​ , last: data[1]
​ , email: data[2]
​ , row: row
​ };
​ Logger.log(user);
​ const res = ui.alert('Send to ' + user.first + '(' + user.email + ')?',
ui.ButtonSet.YES_NO);
​ if (res == ui.Button.YES) {
​ sendUser(user);
​ }
​ Logger.log(res);
​ }

​ function sendUser(user) {
​ //let message = '<h1>Hello World</h1>';
​ const temp = HtmlService.createTemplateFromFile('temp');
​ temp.user = user;
​ const message = temp.evaluate().getContent();
​ MailApp.sendEmail({
​ to: user.email
​ , subject: 'Tester'
​ , htmlBody: message
​ });
​ SpreadsheetApp.getActiveSheet().getRange(user.row, 4).setValue('sent');
​ }

HTML Template

​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ </head>
​ <body>
​ <p style="font-family: fantasy;color:red;font-size:3em">Hi, <?= user.first ?></p>
​ <div>You have been approved</div>
​ <div> Congrats .... <?= user.first ?> <?= user.last ?></div>

​ </body>
​ </html>

Google Sheets Custom API endpoint Data for Web applications


83

​ const SHEETID = '1K4kLsAnxxwWoKoZObTrsNSbP0oqbF_-lAxfXKDspKkQ';


​ const PAGE = 3;
​ function catFinder(e){
​ if('cat' in e.parameters){
​ return e.parameters['cat'][0];
​ }
​ return null;
​ }
​ function pageFinder(e){
​ if('pg' in e.parameters){
​ let num = Number(e.parameters['pg'][0]);
​ if(num){return num; }

​ }
​ return 1;
​ }

​ function doGet(e){
​ const ss = SpreadsheetApp.openById(SHEETID);
​ let cat = catFinder(e) ;
​ let pg = pageFinder(e) ;
​ //let cat = '';
​ //let pg = 2;
​ const sheet = ss.getSheetByName('jokes');
​ const rows = sheet.getDataRange().getValues();
​ const headings = rows[0].map(heading =>{
​ return heading.toString().toLowerCase();
​ })
​ const data = rows.slice(1);
​ let dataObj = makeObj(data,headings);
​ if(cat){
​ dataObj = dataObj.filter(item => item.category === cat);
​ }
​ const start = (pg * PAGE)-PAGE;
​ const myData = dataObj.splice(start,PAGE);
​ myData.forEach(item =>{
​ Logger.log(item);
​ })
​ Logger.log(myData);
​ const pagesTotal = Math.ceil(dataObj.length / PAGE);
​ //Logger.log(headings);
​ //Logger.log(data);
​ return outputContent(myData,pagesTotal,cat,pg);
​ }

​ function makeObj(data,headings){
​ const temp1 = data.map((arr)=>{
​ const obj = {};
​ headings.forEach((heading,index)=>{
​ obj[heading] = arr[index];
​ })
​ return obj;
​ })
84

​ return temp1;
​ }

​ function outputContent(data,pagesTotal,cat,pg){
​ const temp = JSON.stringify({
​ status : 'success',
​ data : data,
​ total : pagesTotal,
​ cats : getCats(),
​ cur: pg,
​ cat : cat
​ })
​ return
ContentService.createTextOutput(temp).setMimeType(ContentService.MimeType.JSON);
​ }


​ function getCats(){
​ const ss = SpreadsheetApp.openById(SHEETID);
​ const sheet = ss.getSheetByName('category');
​ const rows = sheet.getDataRange().getValues();
​ const data = rows.slice(1);
​ const holder = [];
​ data.forEach((el)=>{
​ holder.push(el[0]);
​ })
​ return holder;
​ }

​ <!DOCTYPE html>
​ <html>

​ <head>
​ <title>Sheets API</title>
​ </head>

​ <body>
​ <div class="output"></div>
​ <script>
​ const url =

'https://script.google.com/macros/s/AKfycbze5Eub0EDrSpzLpJph5nbsmTn0L9SrPHLY6QlkeO4O9pE
pOtJRPsp94Zf6djUNyX4-/exec';
​ const cat = 'Sports';
​ const page = 2;
​ const output = document.querySelector('.output');
​ const newURL = url + '?cat=' + cat + '&pg=' + page;
​ loadData();

​ console.log(newURL);

​ function loadData() {
​ fetch(newURL).then(rep => rep.json())
85

​ .then((data) => {
​ console.log(data);
​ data.data.forEach((el) => {
​ console.log(el);
​ output.innerHTML += `${el.id} ${el.content} ${el.response}
<br>`;
​ })
​ })
​ }
​ </script>
​ </body>

​ </html>

Source Code for GmailApp Class labels and inbox messages and threads
example

​ function applyLabel() {
​ const threads = GmailApp.getInboxThreads();
​ const myLabel = 'NEW Email Today';
​ const holder = [];
​ GmailApp.getUserLabels().forEach((labelName)=>{
​ holder.push(labelName.getName());
​ })
​ Logger.log(holder);
​ let tempLabel;
​ if(holder.includes(myLabel)){
​ tempLabel = GmailApp.getUserLabelByName(myLabel);
​ }else{
​ tempLabel = GmailApp.createLabel(myLabel);
​ }
​ Logger.log(tempLabel);
​ threads.forEach((message)=>{
​ //Logger.log(message);
​ const firstMes = message.getFirstMessageSubject();
​ if(firstMes.includes('new')){
​ message.addLabel(tempLabel);
​ message.moveToArchive();
​ message.markRead();
​ }
​ })
​ }

​ function checker(){
​ const tempMessage = GmailApp.getUserLabelByName('NEW Email Today');
​ const threads = tempMessage.getThreads();
​ threads.forEach((thread)=>{
​ thread.markUnread();
​ //thread.reply('Thank you!!!');
​ thread.removeLabel(tempMessage);
​ thread.moveToInbox();
86

​ Logger.log(thread.getMessageCount());
​ const messages = thread.getMessages();
​ messages.forEach((message)=>{
​ Logger.log(message.getSubject());
​ })
​ })
​ }

Update cell properties check for values and data in cells

​ function myFunction() {
​ const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('test');
​ const data = ss.getDataRange().getValues();
​ data.forEach((rowArr,rowIndex)=>{
​ rowArr.forEach((cell,colIndex)=>{
​ if(cell == '6'){
​ Logger.log(rowIndex);
​ const range = ss.getRange(rowIndex+1,colIndex+1);
​ range.setBackground('purple');
​ range.setFontColor('white');
​ range.setFontSize(19);
​ Logger.log(range.getValue());
​ }
​ })
​ })
​ //Logger.log(data);
​ }

Source Code Example Code Create WebApp with Data

​ function doGet(e) {
​ const html = HtmlService.createTemplateFromFile('index');
​ html.dataQ = {
​ arr : [1,2,3,4],
​ val : 5
​ }
​ const output = html.evaluate();
​ return output;
​ }
​ <script>
​ const dataV = <?!= JSON.stringify(dataQ) ?>;
​ console.log(dataV);
​ </script>
​ <!DOCTYPE html>
​ <html>
​ <head>
​ <base target="_top">
​ <style>
​ body{
​ background-color:red;
​ }
87

​ </style>
​ </head>
​ <body>
​ <h1>Hello World V2</h1>
​ <script>
​ console.log('hello');
​ </script>
​ </body>
​ </html>

Source Code apps script example Image and PDF Uploader.

​ function doGet(e) {
​ const html = HtmlService.createTemplateFromFile('index');
​ const output = html.evaluate();
​ return output;
​ }

​ function doUpload(obj){
​ const blob =
Utilities.newBlob(Utilities.base64Decode(obj.data),obj.mimeType,obj.fileName);
​ const id = '1QNw******DExWc8aZD';
​ const folder = DriveApp.getFolderById(id);
​ const file = folder.createFile(blob);
​ const fileURL = file.getUrl();
​ const response = {
​ 'fileName' : obj.fileName,
​ 'url' : fileURL,
​ 'status' :true,
​ 'data' : JSON.stringify(obj)
​ }
​ return response;
​ }

​ <!DOCTYPE html>
​ <html>
​ <head>
​ <title>Uploader V2</title>
​ </head>
​ <body>
​ <h1>Upload your File to Drive</h1>
​ <input type="file" class="uploader">
​ <button class="btn">Upload</button>
​ <div class="output"></div>
​ <script>
​ const btn = document.querySelector('.btn');
​ const output = document.querySelector('.output');
​ const upFile = document.querySelector('.uploader');
​ btn.addEventListener('click',upLoadFile);
​ function upLoadFile(){
​ const upFiles = upFile.files[0];
​ const reader = new FileReader();
88

​ reader.onload = function(e){
​ const vals = reader.result.split(',');
​ const obj = {
​ fileName : upFiles.name,
​ mimeType : upFiles.type,
​ data : vals[1]
​ }
​ //console.log(obj);
​ google.script.run.withSuccessHandler(success).doUpload(obj);
​ }
​ if(upFiles){
​ reader.readAsDataURL(upFiles);
​ }
​ //console.log('ready');
​ }
​ function success(rep){
​ //console.log(rep);
​ const a = document.createElement('a');
​ const linkText = document.createTextNode(rep.fileName);
​ output.append(a);
​ a.append(linkText);
​ a.href = rep.url;
​ a.setAttribute('target','_blank');
​ }
​ </script>
​ </body>
​ </html>

You might also like