Apps Script Code Examples Guide
Apps Script Code Examples Guide
function convertToPlainText() {
// Get the active document
const document = DocumentApp.getActiveDocument();
Send the text version of the Doc using Apps Script to the email
address of the apps script account
function converterText(){
const doc = DocumentApp.openById(ID);
const body = doc.getBody(); //DocumentBodySection
const txt = body.getText();
const email = Session.getActiveUser().getEmail();
//Logger.log(email);
MailApp.sendEmail(email,'My Doc Text',txt);
}
Laurence Svekis https://basescripts.com/
5
Google Sheets add numbers from columns
https://youtu.be/O5PgoPCmcQU
Google Apps Script that adds two numbers and displays the result
in a Google Sheets cell:
function sumTwoNumbers() {
var sheet = SpreadsheetApp.getActiveSheet();
var cell1 = sheet.getRange("A1").getValue();
var cell2 = sheet.getRange("B1").getValue();
var result = cell1 + cell2;
sheet.getRange("C1").setValue(result);
}
Explanation:
var result = cell1 + cell2;: This line creates a variable result and
assigns the sum of cell1 and cell2 to it.
To run this script, you would need to open a Google Sheet and
then open the Apps Script editor by clicking on the "Tools" menu
and selecting "Script editor." Then, paste the code into the editor,
save the script, and run the sumTwoNumbers() function.
function adder(){
const sheet =
SpreadsheetApp.openById(ID).getSheetByName('add');
const data = sheet.getDataRange().getValues();
data.forEach((row,index) =>{
let total = 0;
row.forEach(cell => {
if(cell){
total = total + parseInt(cell);
}
})
const rowValue = index+1;
const range =
sheet.getRange(rowValue,row.length+1,1,1);
range.setValue(total);
})
Laurence Svekis https://basescripts.com/
8
}
function makeNums(){
const ss = SpreadsheetApp.openById(ID);
const sheet = ss.getSheetByName('add');
for(let i=0;i<20;i++){
const arr = [getRan(),getRan(),getRan()];
sheet.appendRow(arr);
}
Logger.log(sheet);
}
function getRan(){
return Math.floor(Math.random()*100);
}
sheet.insertImage(img, 1,1);
}
Explanation:
function imageAdder(){
const ss = SpreadsheetApp.openById(ID);
const sheet = ss.getSheetByName('my');
const imageURL =
'http://www.discoveryvip.com/img/d.png';
const img = UrlFetchApp.fetch(imageURL).getBlob();
sheet.insertImage(img,20,20);
Logger.log(img);
}
function imageAdderCell(){
const ss = SpreadsheetApp.openById(ID);
const sheet = ss.getSheetByName('my');
function helloWorld() {
// This line logs "Hello, world!" to the console
Logger.log("Hello, world!");
}
function hello(){
const message = 'Laurence Svekis';
Logger.log(message);
function addNumbers() {
var num1 = 5;
var num2 = 3;
var result = num1 + num2;
SpreadsheetApp.getUi().alert("The result is: " +
result);
Laurence Svekis https://basescripts.com/
14
}
Explanation:
function showAl(){
const num1 = 100;
const num2 = 144;
const result = num1 + num2;
const output = `The result of ${num1} + ${num2} =
${result}`;
SpreadsheetApp.getUi().alert(output);
}
function calculateAverages() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var total = 0;
for (var i = 0; i < data.length; i++) {
total += data[i][0];
}
var average = total / data.length;
sheet.getRange(data.length + 1, 1).setValue(average);
}
Explanation:
function sheetData2(){
const sheet =
SpreadsheetApp.openById(ID).getSheetByName('data');
const data = sheet.getDataRange().getValues();
const headings = data[0];
const results = data.slice(1);
results.forEach((row,index) => {
const days = (Math.floor(parseInt(row[1])/8));
sheet.getRange(index+2,3).setValue(days);
})
//Logger.log(results);
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
function senderEmail(){
const sheet = SpreadsheetApp
.openById(ID)
.getSheetByName('Users');
const data = sheet.getDataRange().getValues();
const users = data.slice(1);
Logger.log(users);
users.forEach((user,index)=>{
const userName = user[0];
const email = user[2];
const id = user[1];
const message = `Hello ${userName}, your id is
${id}`;
MailApp.sendEmail(email,'Welcome',message);
})
}
Laurence Svekis https://basescripts.com/
20
Explanation:
function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
Explanation:
function emailOut(){
const sheet = SpreadsheetApp.getActiveSheet();
const data = sheet.getDataRange().getValues();
Logger.log(data);
const subject = 'My Update';
const message = 'Hello, \n\nMy update
info!\n\nRegards,\nLaurence Svekis';
for(let i=1;i<data.length;i++){
const email = (data[i][2]);
function formatSheet() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
function formatSheetData(){
const sheet =
SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];
sheet.getRange(1,4,1,1).setValue('Total');
const data = sheet.getDataRange().getValues();
const headerRange =
sheet.getRange(1,1,1,data[0].length);
headerRange.setFontWeight('bold');
headerRange.setFontSize(20);
const borderRange =
sheet.getRange(1,1,data.length,data[0].length);
borderRange.setBorder(true,false,false,true,true,true,'
black',SpreadsheetApp.BorderStyle.DOTTED);
let total = 0;
for(let i=1;i<data.length;i++){
Logger.log(total);
}
function createCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
function updateCalendarEvent() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
Explanation:
The data variable is set to the values of all cells in the active
sheet using the sheet.getDataRange().getValues method.
A for loop is used to iterate through the rows in the data array,
starting from the second row (the first row is assumed to contain
headers).
For each row, the start time, end time, event name, and calendar
ID are stored in the startTime, endTime, eventName, and
calendar variables respectively.
The sheet and data variables are set in the same way as in the
createCalendarEvent function.
A for loop is used to iterate through the rows in the data array,
starting from the second row.
For each row, the event ID is stored in the eventId variable, and
the event is retrieved using the CalendarApp.getEventById
method.
The start time, end time, event name, and calendar ID are stored
in the startTime, endTime, eventName, and calendar variables
respectively.
3/22/2023
Day 1 10:00:00 3/22/2023 12:00:00 online Another Day starts 1
3/23/2023
Day 2 10:00:00 3/23/2023 12:00:00 online Another Day starts 2
3/24/2023
Day 3 10:00:00 3/24/2023 12:00:00 online Another Day starts 3
3/25/2023
Day 4 10:00:00 3/25/2023 12:00:00 online Another Day starts 4
3/26/2023
Day 5 10:00:00 3/26/2023 12:00:00 online Another Day starts 5
const ID = '132trziyLsk8qIk';
function makeEvents(){
const sheet =
SpreadsheetApp.openById(ID).getSheetByName('Cal');
const data = sheet.getDataRange().getValues();
const events = data.slice(1);
const headings = data[0];
events.forEach((event,index)=>{
const start = event[1];
const nameEvent = event[0];
const end = event[2];
const loc = event[3];
function updateCal(){
const cal =CalendarApp.getDefaultCalendar();
const ss = SpreadsheetApp.openById(ID);
const start = new Date();
const end = new Date(start.getTime() +
(100*24*60*60*1000));
const events = cal.getEvents(start,end);
Logger.log(events);
Laurence Svekis https://basescripts.com/
36
const sheet = ss.insertSheet();
sheet.appendRow(['Name','Start','End','Location','ID'])
;
sheet.setName('New Event List');
events.forEach(event => {
const arr =
[event.getTitle(),event.getStartTime(),event.getEndTime
(),event.getLocation(),event.getId()];
sheet.appendRow(arr);
})
}
function copyToCalendar() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var calendar =
CalendarApp.getCalendarById("your_calendar_id");
function logAttachments() {
var threads = GmailApp.search("has:attachment");
Explanation:
function getAtt(){
const id = '132trvLa8IvLsk8qIk';
})
Google Apps Script that creates a new folder in Google Drive for
each row in a Google Sheet and stores a PDF file with the
contents of a specific column in that folder:
function createFoldersAndFiles() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var parentFolder =
DriveApp.getFolderById("your_parent_folder_id");
function makeFolderDrive(){
const folder = DriveApp.createFolder('attachments');
const threads = GmailApp.search('has:attachment');
const attachments = [];
threads.forEach(thread => {
thread.getMessages().forEach(message => {
message.getAttachments().forEach(attachment => {
const file =
folder.createFile(attachment.copyBlob().setName(attachm
ent.getName()));
attachments.push(attachment.getName());
})
})
})