Apps Script Coding Examples
Google Apps Script is a scripting platform that lets you extend
Google Workspace by adding custom functionality to your Google
Sheets, Docs, Forms, and Gmail. Google Apps Script is a
cloud-based scripting language that provides easy ways to
automate tasks across Google products and third-party services.
Top Tips for Google Apps Script 2
Converting a Google Document to plain text 4
Google Sheets add numbers from columns 6
Sheet Data and Cell Values 7
Add Image to Sheet Cell 9
New CellImage in Sheets 11
Laurence Svekis [Link]
1
Logging to the console 12
Adding numbers and showing an alert 14
Read Data from from Sheet 16
Get sheet data - apply changes and set value in sheet data 18
Send email from Sheet 19
Use Sheet data for custom emails out 20
Send Emails to recipients from Sheet data 22
Send emails from User list in Sheets 23
Sending an email to all users from the spreadsheet data 25
Apps Script on Sheets examples 26
Using Sheet data create a chart update styling 29
Apps Script Create Calendar entries from Sheet data 31
Sheet data to create Calendar events 35
Calendar Events into Sheet 36
Sheet data to populate Calendar 37
Logs Email Attachments details 39
Get Gmail Attachments Log into Sheet 41
Create folder in drive from Sheet Data 43
Get attachments from Gmail and Copy To Drive 45
Top Tips for Google Apps Script
10 tips to help you improve your Google Apps Script coding:
Laurence Svekis [Link]
2
1. Use the Google Apps Script Debugger: Google Apps Script
has a built-in debugger that can help you find and fix errors
in your code.
2. Test your code with sample data: Before you run your code
on real data, test it with a small set of sample data to make
sure it works as expected.
3. Use proper naming conventions: Naming your variables and
functions in a consistent and descriptive manner will make
your code easier to read and understand.
4. Comment your code: Adding comments to your code will
help you (and others) understand what your code is doing,
especially if it's complex.
5. Use arrays and objects effectively: Arrays and objects are
powerful data structures in Google Apps Script. Learn how to
use them effectively to simplify your code and make it more
readable.
6. Use built-in functions and methods: Google Apps Script has
many built-in functions and methods that you can use to
perform common tasks. Take advantage of these to save
time and make your code more efficient.
7. Avoid hardcoding values: Avoid hardcoding values in your
code, such as cell references or URLs, as this can make your
code difficult to maintain. Instead, use variables and
functions to make your code more flexible.
Laurence Svekis [Link]
3
8. Use error handling: Use error handling techniques to handle
unexpected errors and keep your code running smoothly.
9. Write modular code: Write modular code by breaking your
code into small, reusable functions that can be used in
multiple places.
10. Keep your code organized: Keeping your code organized
by using proper indentation, separating code into different
functions and sections, and using meaningful variable names
will make it easier to read, understand, and maintain.
Converting a Google Document to plain text
[Link]
Converting a Google Document to plain text:
function convertToPlainText() {
// Get the active document
const document = [Link]();
// Get the body of the document
const body = [Link]();
// Get the plain text representation of the document
const plainText = [Link]();
Laurence Svekis [Link]
4
// Log the plain text to the console
[Link](plainText);
}
In this example, the convertToPlainText() function uses the
DocumentApp class to convert a Google Document to plain text.
The [Link]() method is used to get
the active document, and the [Link]() method is
used to get the body of the document. The [Link]()
method is then used to get the plain text representation of the
document, which is logged to the console using the [Link]()
method.
Send the text version of the Doc using Apps Script to the email
address of the apps script account
function converterText(){
const doc = [Link](ID);
const body = [Link](); //DocumentBodySection
const txt = [Link]();
const email = [Link]().getEmail();
//[Link](email);
[Link](email,'My Doc Text',txt);
}
Laurence Svekis [Link]
5
Google Sheets add numbers from columns
[Link]
Google Apps Script that adds two numbers and displays the result
in a Google Sheets cell:
function sumTwoNumbers() {
var sheet = [Link]();
var cell1 = [Link]("A1").getValue();
var cell2 = [Link]("B1").getValue();
var result = cell1 + cell2;
[Link]("C1").setValue(result);
}
Explanation:
function sumTwoNumbers(): This is the declaration of the function
sumTwoNumbers, which contains the code that will be executed.
var sheet = [Link]();: This line creates
a variable sheet and assigns the active sheet to it using the
[Link]() method.
Laurence Svekis [Link]
6
var cell1 = [Link]("A1").getValue();: This line creates a
variable cell1 and assigns the value of cell A1 to it using the
getValue() method.
var cell2 = [Link]("B1").getValue();: This line creates a
variable cell2 and assigns the value of cell B1 to it using the
getValue() method.
var result = cell1 + cell2;: This line creates a variable result and
assigns the sum of cell1 and cell2 to it.
[Link]("C1").setValue(result);: This line sets the value
of cell C1 to the value of result using the setValue() method.
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.
Sheet Data and Cell Values
[Link]
Adding numbers together, creating random numbers to populate
the sheet data.
Laurence Svekis [Link]
7
const ID = '132trk8qIk';
function adder(){
const sheet =
[Link](ID).getSheetByName('add');
const data = [Link]().getValues();
[Link]((row,index) =>{
let total = 0;
[Link](cell => {
if(cell){
total = total + parseInt(cell);
}
})
const rowValue = index+1;
const range =
[Link](rowValue,[Link]+1,1,1);
[Link](total);
})
Laurence Svekis [Link]
8
}
function makeNums(){
const ss = [Link](ID);
const sheet = [Link]('add');
for(let i=0;i<20;i++){
const arr = [getRan(),getRan(),getRan()];
[Link](arr);
}
[Link](sheet);
}
function getRan(){
return [Link]([Link]()*100);
}
Add Image to Sheet Cell
[Link]
add an image to a cell in a Google Sheets spreadsheet using
Google Apps Script:
Laurence Svekis [Link]
9
function addImageToCell() {
var sheet = [Link]();
var imageUrl = "[Link]
var img = [Link](imageUrl).getBlob();
[Link](img, 1,1);
}
Explanation:
First, we get a reference to the active sheet using
[Link]().
Next, we get a reference to the cell where we want to insert the
image using [Link]("A1"). You can specify any cell you
want by changing the argument to getRange().
Then, we specify the URL of the image we want to insert using
the imageUrl variable.
We use the [Link]() method to retrieve the image
data from the specified URL. This method returns a Response
object, which we get the binary data (the image) from using
getBlob().
Laurence Svekis [Link]
10
Finally, we use the [Link]() method to insert the
image into the specified cell. The first argument is the image data
(the blob we obtained in step 4), and the second argument is the
cell reference.
function imageAdder(){
const ss = [Link](ID);
const sheet = [Link]('my');
const imageURL =
'[Link]
const img = [Link](imageURL).getBlob();
[Link](img,20,20);
[Link](img);
}
New CellImage in Sheets
To add an image into a specific cell this can be done using the
newCellImage method.
function imageAdderCell(){
const ss = [Link](ID);
const sheet = [Link]('my');
Laurence Svekis [Link]
11
const range = [Link](1,1,3,3);
const imageURL =
'[Link]
const image = SpreadsheetApp
.newCellImage()
.setSourceUrl(imageURL)
.setAltTextTitle('discoveryvip')
.build();
[Link](image);
}
Logging to the console
[Link]
basic syntax and structure of a Google Apps Script.
function helloWorld() {
// This line logs "Hello, world!" to the console
[Link]("Hello, world!");
}
Laurence Svekis [Link]
12
This is a simple function named helloWorld that logs the string
"Hello, world!" to the Google Apps Script logging console.
Here's what's happening in this example:
The function keyword declares that this is a function.
The helloWorld function name follows the function keyword.
The code inside the curly braces {} is the body of the function.
The [Link] statement logs the message "Hello, world!" to the
console.
You can run this script by selecting the code and clicking the
"Run" button in the Google Apps Script editor, or by pressing Ctrl
+ Enter (Cmd + Enter on a Mac). When you run this script, the
message "Hello, world!" will appear in the logging console.
This is just a simple example, but Google Apps Script provides a
wide range of functionality that you can use to automate tasks,
manipulate data, and interact with other Google Workspace
services. With a little bit of code, you can streamline your work
and save yourself a lot of time.
function hello(){
const message = 'Laurence Svekis';
[Link](message);
Laurence Svekis [Link]
13
for(let i=0;i<20;i++){
[Link](i);
}
}
Adding numbers and showing an alert
Sheets Add Numbers UI Alert.
Google Apps Script that adds up two numbers and displays the
result in a dialog box:
function addNumbers() {
var num1 = 5;
var num2 = 3;
var result = num1 + num2;
[Link]().alert("The result is: " +
result);
Laurence Svekis [Link]
14
}
Explanation:
The function addNumbers is defined.
Two variables num1 and num2 are defined and assigned values of
5 and 3 respectively.
The result of num1 + num2 is calculated and stored in the
variable result.
The [Link]().alert method is used to display a
dialog box with the text "The result is: 8", which is the value of
the result variable.
This script can be run in a Google Spreadsheet by opening the
script editor (under the "Tools" menu), copying and pasting the
code into the editor, and then clicking the "Run" button
function showAl(){
const num1 = 100;
const num2 = 144;
const result = num1 + num2;
const output = `The result of ${num1} + ${num2} =
${result}`;
[Link]().alert(output);
}
Laurence Svekis [Link]
15
Read Data from from Sheet
[Link]
Google Apps Script that reads data from a Google Sheet,
performs calculations on the data, and writes the results back to
the sheet:
function calculateAverages() {
var sheet = [Link]();
var data = [Link]().getValues();
var total = 0;
for (var i = 0; i < [Link]; i++) {
total += data[i][0];
}
var average = total / [Link];
[Link]([Link] + 1, 1).setValue(average);
}
Explanation:
The function calculateAverages is defined.
Laurence Svekis [Link]
16
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().getValues method.
A for loop is used to sum up the values in the first column of the
data array. The total variable is used to keep track of the sum.
The average value is calculated by dividing the total by the
number of rows in the data ([Link]).
The average value is written to the next empty row in the first
column of the sheet using the [Link]([Link] + 1,
1).setValue method.
This script can be run in a Google Spreadsheet by opening the
script editor (under the "Tools" menu), copying and pasting the
code into the editor, and then clicking the "Run" button. It will
read the data in the sheet, perform the calculation, and write the
result to the next empty row in column A.
Laurence Svekis [Link]
17
Get sheet data - apply changes and set value in sheet
data
function sheetData2(){
const sheet =
[Link](ID).getSheetByName('data');
const data = [Link]().getValues();
const headings = data[0];
const results = [Link](1);
[Link]((row,index) => {
const days = ([Link](parseInt(row[1])/8));
[Link](index+2,3).setValue(days);
})
//[Link](results);
Laurence Svekis [Link]
18
Send email from Sheet
[Link]
Google Apps Script that sends an email based on the contents of
a Google Sheet:
function sendEmails() {
var sheet = [Link]();
var data = [Link]().getValues();
for (var i = 1; i < [Link]; i++) {
var emailAddress = data[i][0];
var message = data[i][1];
var subject = "Important Message";
[Link](emailAddress, subject, message);
}
}
Laurence Svekis [Link]
19
Use Sheet data for custom emails out
function senderEmail(){
const sheet = SpreadsheetApp
.openById(ID)
.getSheetByName('Users');
const data = [Link]().getValues();
const users = [Link](1);
[Link](users);
[Link]((user,index)=>{
const userName = user[0];
const email = user[2];
const id = user[1];
const message = `Hello ${userName}, your id is
${id}`;
[Link](email,'Welcome',message);
})
}
Laurence Svekis [Link]
20
Explanation:
The function sendEmails is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().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 email address is stored in the emailAddress
variable, the message text is stored in the message variable, and
the subject of the email is set to "Important Message".
Laurence Svekis [Link]
21
The [Link] method is used to send an email to the
address stored in emailAddress, with the subject and message
stored in subject and message respectively.
This script can be run in a Google Spreadsheet by opening the
script editor (under the "Tools" menu), copying and pasting the
code into the editor, and then clicking the "Run" button. It will
read the data in the sheet, send an email to each email address
specified in column A, with the message specified in column B.
Send Emails to recipients from Sheet data
Google Apps Script that sends an email to a list of recipients
based on data in a Google Sheet:
function sendEmails() {
var sheet = [Link]();
var data = [Link]().getValues();
for (var i = 1; i < [Link]; i++) {
var email = data[i][0];
var subject = data[i][1];
var message = data[i][2];
Laurence Svekis [Link]
22
[Link](email, subject, message);
}
}
Explanation:
The function sendEmails is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().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 email address, subject, and message are stored
in the email, subject, and message variables respectively.
An email is sent to the recipient specified by email using the
[Link] method, with the subject and message
specified by subject and message respectively.
Send emails from User list in Sheets
Google Apps Script that sends an email to a list of recipients from
a Google Sheet:
Laurence Svekis [Link]
23
function sendEmails() {
var sheet = [Link]();
var data = [Link]().getValues();
var subject = "Important Update";
var message = "Hello,\n\nThis is an important update.
Please read carefully.\n\nBest regards,\nYour Name";
for (var i = 1; i < [Link]; i++) {
var email = data[i][0];
[Link](email, subject, message);
}
}
Explanation:
The function sendEmails is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().getValues method.
The subject and message variables are set to the subject and
message of the email respectively.
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).
Laurence Svekis [Link]
24
For each row, the email address is stored in the email variable.
An email is sent to the recipient using the [Link]
method, with the recipient's email address, subject, and message
specified by email, subject, and message respectively.
Sending an email to all users from the spreadsheet data
function emailOut(){
const sheet = [Link]();
const data = [Link]().getValues();
[Link](data);
const subject = 'My Update';
const message = 'Hello, \n\nMy update
info!\n\nRegards,\nLaurence Svekis';
for(let i=1;i<[Link];i++){
const email = (data[i][2]);
Laurence Svekis [Link]
25
[Link](email,subject,message);
}
}
Apps Script on Sheets examples
[Link]
Google Apps Script that performs various operations on a Google
Sheet, including formatting cells, calculating values, and creating
charts:
function formatSheet() {
var sheet = [Link]();
var data = [Link]().getValues();
// Format the header row in bold
var headerRange = [Link](1, 1, 1,
data[0].length);
[Link]("bold");
// Add borders to all cells
var borderRange = [Link](1, 1, [Link],
data[0].length);
Laurence Svekis [Link]
26
[Link](true, true, true, true, null,
null);
// Calculate the sum of the values in column 1
var sum = 0;
for (var i = 1; i < [Link]; i++) {
sum += data[i][0];
}
// Write the sum to the bottom of column 1
[Link]([Link] + 1, 1).setValue(sum);
// Create a chart to visualize the data
var chart = [Link]()
.setChartType([Link])
.addRange([Link](1, 1, [Link], 1))
.setOption('title', 'Column 1 Data')
.setOption('width', 400)
.setOption('height', 300)
.setPosition(5,6,0,0)
.build();
[Link](chart);
}
Laurence Svekis [Link]
27
Explanation:
The function formatSheet is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().getValues method.
The header row is formatted in bold by getting the range of cells
in the first row and using the setFontWeight method to set the
font weight to "bold".
Borders are added to all cells by getting the range of all cells and
using the setBorder method to set all borders to true.
The sum of the values in column 1 is calculated using a for loop
and stored in the sum variable.
The sum is written to the bottom of column 1 using the
[Link]([Link] + 1, 1).setValue method.
A bar chart is created to visualize the data in column 1 using the
Charts service and the [Link] method. The chart
options, such as the title and dimensions, are set using the
setOption method. The chart is inserted into the sheet using the
[Link] method.
This script can be run in a Google Spreadsheet by opening the
script editor (under the "Tools" menu), copying and pasting the
code into the editor, and then clicking the "Run" button. It will
Laurence Svekis [Link]
28
format the cells in the sheet, calculate the sum of the values in
column 1, and insert a chart to visualize the data.
Using Sheet data create a chart update
styling
function formatSheetData(){
const sheet =
[Link]().getSheets()[1];
[Link](1,4,1,1).setValue('Total');
const data = [Link]().getValues();
const headerRange =
[Link](1,1,1,data[0].length);
[Link]('bold');
[Link](20);
const borderRange =
[Link](1,1,[Link],data[0].length);
[Link](true,false,false,true,true,true,'
black',[Link]);
let total = 0;
for(let i=1;i<[Link];i++){
Laurence Svekis [Link]
29
let sum = parseInt(data[i][1]) *
parseInt(data[i][2]);
[Link](i+1,4,1,1).setValue(sum);
[Link](sum);
total += sum;
}
[Link]([Link]+1,4,1,1).setValue(total);
const myChart = [Link]()
.setChartType([Link])
.addRange([Link]('B2:C7'))
.setOption('title','My Data')
.setOption('width',500)
.setOption('height',400)
.setPosition(5,6,0,0)
.build();
[Link](myChart)
[Link](total);
}
Laurence Svekis [Link]
30
Apps Script Create Calendar entries from
Sheet data
[Link]
Google Apps Script that automatically creates and updates a
Google Calendar event based on data in a Google Sheet:
function createCalendarEvent() {
var sheet = [Link]();
var data = [Link]().getValues();
for (var i = 1; i < [Link]; i++) {
var startTime = data[i][0];
Laurence Svekis [Link]
31
var endTime = data[i][1];
var eventName = data[i][2];
var calendar =
[Link](data[i][3]);
var event = [Link](eventName,
startTime, endTime);
}
}
function updateCalendarEvent() {
var sheet = [Link]();
var data = [Link]().getValues();
for (var i = 1; i < [Link]; i++) {
var eventId = data[i][4];
var event = [Link](eventId);
var startTime = data[i][0];
var endTime = data[i][1];
var eventName = data[i][2];
var calendar =
[Link](data[i][3]);
Laurence Svekis [Link]
32
[Link](eventName);
[Link](startTime);
[Link](endTime);
[Link](calendar);
}
}
Explanation:
The function createCalendarEvent is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().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.
Laurence Svekis [Link]
33
A new event is created in the calendar specified by calendar using
the [Link] method, with the start time, end time,
and event name specified by startTime, endTime, and eventName
respectively.
The function updateCalendarEvent is defined.
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 [Link]
method.
The start time, end time, event name, and calendar ID are stored
in the startTime, endTime, eventName, and calendar variables
respectively.
The event is updated using the setTitle, setStartTime,
setEndTime, and setCalendar methods
Laurence Svekis [Link]
34
Sheet data to create Calendar events
Event Start End Location Description
3/22/2023
Day 1 [Link] 3/22/2023 [Link] online Another Day starts 1
3/23/2023
Day 2 [Link] 3/23/2023 [Link] online Another Day starts 2
3/24/2023
Day 3 [Link] 3/24/2023 [Link] online Another Day starts 3
3/25/2023
Day 4 [Link] 3/25/2023 [Link] online Another Day starts 4
3/26/2023
Day 5 [Link] 3/26/2023 [Link] online Another Day starts 5
const ID = '132trziyLsk8qIk';
function makeEvents(){
const sheet =
[Link](ID).getSheetByName('Cal');
const data = [Link]().getValues();
const events = [Link](1);
const headings = data[0];
[Link]((event,index)=>{
const start = event[1];
const nameEvent = event[0];
const end = event[2];
const loc = event[3];
Laurence Svekis [Link]
35
const des = event[4];
const cal =[Link]();
const eve = [Link](nameEvent,start,end,{
location:loc,
description:des
});
[Link](cal);
})
}
Calendar Events into Sheet
function updateCal(){
const cal =[Link]();
const ss = [Link](ID);
const start = new Date();
const end = new Date([Link]() +
(100*24*60*60*1000));
const events = [Link](start,end);
[Link](events);
Laurence Svekis [Link]
36
const sheet = [Link]();
[Link](['Name','Start','End','Location','ID'])
;
[Link]('New Event List');
[Link](event => {
const arr =
[[Link](),[Link](),[Link]
(),[Link](),[Link]()];
[Link](arr);
})
}
Sheet data to populate Calendar
Google Apps Script that copies the data from a Google Sheet to a
Google Calendar:
function copyToCalendar() {
var sheet = [Link]();
var data = [Link]().getValues();
var calendar =
[Link]("your_calendar_id");
Laurence Svekis [Link]
37
for (var i = 1; i < [Link]; i++) {
var date = data[i][0];
var eventName = data[i][1];
var description = data[i][2];
var start = new Date(date);
var end = new Date(date);
[Link]([Link]() + 1);
[Link](eventName, start, end, { description:
description });
}
}
Explanation:
The function copyToCalendar is defined.
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().getValues method.
The calendar variable is set to the calendar with the specified ID
using the [Link] method. Replace
"your_calendar_id" with the actual ID of your calendar.
Laurence Svekis [Link]
38
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 date, event name, and description are stored in
the date, eventName, and description variables respectively.
The start variable is set to a new date object created from the
date variable.
The end variable is set to a new date object created from the date
variable, with the number of hours increased by 1.
A new event is created in the calendar using the
[Link] method, with the event name, start and end
times, and description specified by eventName, start, end, and
description respectively.
Logs Email Attachments details
[Link]
Google Apps Script that logs information about all attachments in
a Gmail account:
function logAttachments() {
var threads = [Link]("has:attachment");
for (var i = 0; i < [Link]; i++) {
var messages = threads[i].getMessages();
Laurence Svekis [Link]
39
for (var j = 0; j < [Link]; j++) {
var attachments = messages[j].getAttachments();
for (var k = 0; k < [Link]; k++) {
var attachment = attachments[k];
var fileName = [Link]();
var size = [Link]();
[Link]("Attachment: " + fileName + " -
Size: " + size + " bytes");
}
}
}
}
Explanation:
The function logAttachments is defined.
The threads variable is set to an array of all threads in the Gmail
account that have attachments, using the [Link]
method with the query "has:attachment".
A for loop is used to iterate through the threads in the threads
array.
Laurence Svekis [Link]
40
For each thread, the messages variable is set to an array of all
messages in the thread using the threads[i].getMessages
method.
Another for loop is used to iterate through the messages in the
messages array.
For each message, the attachments variable is set to an array of
all attachments in the message using the
messages[j].getAttachments method.
Another for loop is used to iterate through the attachments in the
attachments array.
For each attachment, the fileName and size variables are set to
the name and size of the attachment respectively, using the
[Link] and [Link] methods.
The information about the attachment is logged to the Google
Apps Script log using the [Link] method.
Get Gmail Attachments Log into Sheet
function getAtt(){
const id = '132trvLa8IvLsk8qIk';
Laurence Svekis [Link]
41
const threads = [Link]('has:attachment');
const ss = [Link](id);
const sheet = [Link]();
[Link]('Attachments');
[Link](thread =>{
const messages = [Link]();
[Link](message => {
const attments = [Link]();
[Link](attachment =>{
[Link]([Link]());
const arr =
[[Link](),[Link](),attachment.g
etContentType()];
[Link](arr);
})
})
})
Laurence Svekis [Link]
42
Create folder in drive from Sheet Data
[Link]
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 = [Link]();
var data = [Link]().getValues();
var parentFolder =
[Link]("your_parent_folder_id");
for (var i = 1; i < [Link]; i++) {
var folderName = data[i][0];
var contents = data[i][1];
var folder = [Link](folderName);
var file = [Link]("[Link]", contents,
[Link]);
}
}
Explanation:
The function createFoldersAndFiles is defined.
Laurence Svekis [Link]
43
The sheet variable is set to the active sheet in the current
spreadsheet using the [Link] method.
The data variable is set to the values of all cells in the active
sheet using the [Link]().getValues method.
The parentFolder variable is set to the folder with the specified ID
using the [Link] method. Replace
"your_parent_folder_id" with the actual ID of your parent folder.
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 folder name and contents are stored in the
folderName and contents variables respectively.
A new folder is created in the parent folder using the
[Link] method and the folder name is specified
by folderName.
A new file with the contents of the contents variable is created in
the new folder using the [Link] method, with the file
name "[Link]" and MIME type PDF specified by
"[Link]" and [Link] respectively.
Laurence Svekis [Link]
44
Get attachments from Gmail and Copy To
Drive
function makeFolderDrive(){
const folder = [Link]('attachments');
const threads = [Link]('has:attachment');
const attachments = [];
[Link](thread => {
[Link]().forEach(message => {
[Link]().forEach(attachment => {
const file =
[Link]([Link]().setName(attachm
[Link]()));
[Link]([Link]());
})
})
})
Laurence Svekis [Link]
45
[Link](attachments);
}
Laurence Svekis [Link]
46