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

How To Use Python To Automate Google Sheets - (2024 Edition)

Uploaded by

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

How To Use Python To Automate Google Sheets - (2024 Edition)

Uploaded by

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

5/3/24, 7:08 PM How to Use Python to Automate Google Sheets?

(2024 Edition)

Become a Certified GenAI Professional: 10+ Real-world


Projects, 26+ GenAI Libraries, 75+ Mentorship Sessions
Explore Program

Home Beginner
How to Use Python to Automate Google Sheets? (2024 Edition)

How to Use Python to Automate


Google Sheets? (2024 Edition)
L Lakshay Arora
24 Apr, 2024 • 8 min read

Introduction
Automation of work has been one of the quickest ways to
reach functional efficiency. Moreover, in today’s era where
success is dependent on speed, automation of myriad
repetitive tasks plays a key role in any industry and at the
most basic level of functionality. But many of us fail to
understand how to automate tasks and end up in the loop
of manually doing the same things again. One such skill
you can learn is to use python to automate certain
functions in Google sheets.
This article will show a step-by-step process to set up a
Google service account. We will use python to read
google sheets’ data with the help of Google APIs and will
also update the data in the spreadsheet using python
google sheets. We will read the cricket commentary data
from the spreadsheet, find out the number of runs scored
by each batsman, and then upload the results into a
separate spreadsheet.

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 1/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)
Prerequisite:
12
This tutorial requires you to install Python 3 and Pip3 on
your local computer. To install Python, In case you are
unfamiliar with Python, do have a look at our free course
Introduction to Python
Learning Objectives
1. This tutorial helps you reduce manual work daily is
reduced and just one click script away.
2. Help you gain knowledge of python and google sheets
(gsheets).
3. It might help you to create a new project and python
script to save a lot of time.
4. You Will Get help to accommodate about Python
Google Sheets or How to read google sheet in python.
Participate and become a part of 800+ data science
authors. Register Now

Table of contents

Can we Automate Data Entry Into Google


Sheets?
We often spend hours daily extracting data and then
copy-pasting it to spreadsheets and creating reports
leading to excessive time consumption. Consequently, it
would be great if we just run a script, the data is uploaded
in the spreadsheet, and the report is prepared with just a
click. There are multiple advantages of report automation,
such as being able to save time on data collection and
removing typos, and focus would be more on the analysis
part. Let’s find out how we can do this.
How to Upload Python Data Into Google
Sheets?
There are several ways to get Python code to output to
Google Sheets.

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 2/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

12

Using Python Google API Client is one of the easiest


ways.
We can use these two pip packages, and there are
others as well
Gsheets
Gspread
However, we are using gspread in this tutorial.
How to Create a Google Service Account?
In order to read and update the data from google
spreadsheets in python, we will have to create a Service
Account. It is a special type of account used to make
authorized API calls to Google Cloud Services – Google
Cloud Docs.
First of all, make sure that you have a google account. If
you have a Google account, you can follow these steps to
create a Google service account.
1. Go to the developer’s console. Now, you will see
something like this. Click on the Create Project button.

2. Then provide the project name and the organization


name, which is optional. Then click on the create
button.

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 3/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

3. Now that our project is created, we need to enable the


12 require in this project. Click on the Enable
APIs that we
APIs and Services button to search for the APIs that
Google provides.

Consequently, we will add two APIs for our project.


Google Sheets API
Google Drive API
4. Then, in the search bar, search for these APIs and
click on the enable button.

5. Google Sheets API will look something like this. It will


allow you to access Google Spreadsheets. You would
be able to read and modify the content present in the
Spreadsheets.

Google Drive API will look something like this. It will


allow you to access the resources from Google Drive.

6. Once you have enabled the required APIs in your


project, then it’s time to create credentials for the
service account. Click on the Create Credentials
button to continue.

7. Now, select Google Drive API in the type of API


required question. We will call the API from a non-UI-
based platform, so select Other non-UI (e.g., cron job,
daemon). Select the ‘Application Data’ in the next
https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 4/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

question, as we do not require any user data to run our


application.12 And also, we are not using any cloud-
based computing engine for our application. Finally,
click on the ‘What credentials do I need?’ button.

8. Then, share the google spreadsheets with others and


provide permission like edit or view only. Similarly, we
will provide access to our service account. We will give
it complete access so that we can read and write the
spreadsheets and download the credentials.json file of
the credentials.

A JSON file will now be downloaded, containing the keys


to access the API. Our google service account is ready to
use. In the next section, we will read and modify the data
in the google spreadsheet.
How to Read Data From Google Sheets
Using Python?
https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 5/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

We will read the commentary data of the India-


12 match. You can access the data (.csv)
Bangladesh cricket
from here.

We have ball-by-ball data of the complete match in the


spreadsheet. Now, we will do a fundamental task and
calculate how many runs are scored by each batsman. We
can do this by using a simple groupby in pandas. And
finally, we will append the results in a separate sheet.
Provide access to the Google sheet.
Now, we need to provide access to the google sheet so
that the API can access it. Open the JSON file that we
downloaded from the developer’s console. Look for the
client_email in the JSON file and copy it.

Then click on the Share button on the Spreadsheet and


provide access to this client email.

Now, we are ready to use python to code and access the


google sheet data. The following are the steps:
1. Import libraries
We will use the gspread and oauth2client services to
authorize and make API calls to Google Cloud Services.
You can use the following code to install gspread and
oauth2 python libraries.
https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 6/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)
!pip3 install gspread
!
12
pip3 install --upgrade google-api-python-client oauth2client

Python Code:

2. Define the scope of the application


Then, we will define the scope of the application and add
the JSON file with the credentials to access the API.
1 # define the scope
2 scope = ['https://spreadsheets.google.com/feeds','https://www.googlea
3
4 # add credentials to the account
5 creds = ServiceAccountCredentials.from_json_keyfile_name('add_json_fi
6
7 # authorize the clientsheet
8 client = gspread.authorize(creds)

new_scope.py hosted with by GitHub view raw

3. Create the sheet instance


Use the client object and open the sheet. You can either
pass the title of the sheet as the argument or pass the
URL of the sheet.
Access a particular sheet: We have multiple sheets in a
single spreadsheet. You can use python to access
particular google sheets by providing the index of that
sheet in the get_worksheet function. For the first sheet,
pass the index 0 and so on.
1 # get the instance of the Spreadsheet
2 sheet = client.open('commentary data')
3
4 # get the first sheet of the Spreadsheet
5 sheet_instance = sheet.get_worksheet(0)

client.py hosted with by GitHub view raw

Basic functionalities
https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 7/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

The API provides some basic functionalities, such as the


12 by using col_count and get the value
number of columns
in a particular cell. Here are some examples of the same.
1 # get the total number of columns
2 sheet_instance.col_count
3 ## >> 26
4
5
6 # get the value at the specific cell
7 sheet_instance.cell(col=3,row=2)
8 ## >> <Cell R2C3 '63881'>

cell.py hosted with by GitHub view raw

4. Get all records


Then, we will get all the data in the sheet using the
get_all_records function. It will return a JSON string
containing the data.
1 # get all the records of the data
2 records_data = sheet_instance.get_all_records()
3
4 # view the data
5 records_data

get_records.py hosted with by GitHub view raw

5. Convert the dictionary to the dataframe


In data science, pandas is one of the most preferred
libraries for data manipulation tasks. So we will first
convert the JSON string to the pandas dataframe.
In case you are not comfortable with the pandas, I would
highly recommend you to enroll in this free course:
Pandas for Data Analysis in Python
1 # convert the json to dataframe
2 records_df = pd.DataFrame.from_dict(records_data)
3
4 # view the top records
5 records_df.head()

df.py hosted with by GitHub view raw

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 8/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

12

6. Grouping batsman
Then, we will create a groupby of the number of runs
scored by a batsman and upload that dataframe in a
separate sheet.
1 # number of runs by each batsman
2 runs = records_df.groupby(['Batsman_Name'])['Runs'].count().reset_ind
3 runs

runs.py hosted with by GitHub view raw

Now, we will add this dataframe to google sheets.


Update Data in Google Sheets
The following are steps to update data in google sheets.
1. Create a separate sheet.
Firstly, we will create a separate sheet to store the
results. For that, use the add_worksheet function and
pass the number of rows and columns required and
the sheet’s title. After that, get the instance of the
second sheet by providing the index, which is 1.Once
you run this command, you will see that a separate
sheet has been created.
2. https://gist.github.com/lakshay-
arora/a7aee14b6e3a8296c6b100d49cd86031#file-
https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 9/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

add_sheet-py
12

3. Update values to the sheet


Then, convert the runs dataframe into the 2-D list and
use the function to add values in the sheet. With this
single line of code, you can update the sheet. Then,
you will get a message of the number of rows and
columns updated with some more
details.https://gist.github.com/lakshay-
arora/a7aee14b6e3a8296c6b100d49cd86031#file-
insert_into_sheet-py

Conclusion
To summarize, in this article, we delved into
understanding the various steps involved in the process of

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 10/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

creating a service account. And how to read and write in


Google Sheets12right from your Python console using the
Python Google Sheets API. We downloaded the
spreadsheet data, converted it into a pandas dataframe,
created a groupby table, and uploaded it to the
spreadsheet again. This API can be beneficial in the
automation of reports.
In case you want to brush up on your spreadsheet
concepts, I recommend the following article and course-
Microsoft Excel: Formulas & Functions
10+ Simple Yet Powerful Excel Tricks for Data Analysis
Key Takeaways
Google spreadsheets are essential in almost every
industry and help others see the changes.
It will help in acquiring knowledge of python
programming and scripting.
It saves a lot of time using python libraries by reducing
manual work with the help of scripting.
Frequently Asked Questions
analytics python automation Excel spreadsheets
google sheets programming report automation

L Lakshay Arora
24 Apr 2024

Beginner Excel Programming Python

Frequently Asked Questions


Q1. How to read data from Google spreadsheets with
Python?
A. We can use gspread and oauth2 python libraries for
reading excel files and spreadsheets. More ways of reading
data from Google spreadsheets using Python are explained
in the above article.

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 11/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

Q2. What is the


12 use of Google spreadsheet?

Q3. Can we do python programming and machine learning


vscode?

Q4. Can you do coding in Google Sheets?

Q5. Can we automate Google sheet?

Responses From Readers


What are your thoughts?...

Submit reply

puneet wadhwa
01 Aug, 2020
Hi, unable to open commentary data from spyder,
console throws SpreadsheetNotFound error. while
sharing the spreadsheet on email in the json file the
mail bounced back.
1 Show 1 reply
Stalin R
26 Oct, 2020
Bro thankyou very much. It worked...

EMINA TUZOVIC
29 Oct, 2020
Hi, unable to open commentary data from spyder,
console throws SpreadsheetNotFound error. while
sharing the spreadsheet on email in the json file the

Write for us
Write, captivate, and earn accolades and rewards for your
work

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 12/13
5/3/24, 7:08 PM How to Use Python to Automate Google Sheets? (2024 Edition)

Reach a Global Audience


12 Feedback
Get Expert
Build Your Brand & Audience
Cash In on Your Knowledge
Join a Thriving Community
Level Up Your Data Science Game

CHIRAG GOYAL Barney Darlin


87 5

Company Discover
About Us Blogs
Contact Us Expert session
Careers Podcasts
Comprehensive Guides
Learn Engage
Free courses Community
Learning path Hackathons
BlackBelt program Events
Gen AI Daily challenges
Contribute Enterprise
Contribute & win Our offerings
Become a speaker Case studies
Become a mentor Industry report
Become an instructor quexto.ai

Download App

Terms & conditions Refund Policy Privacy Policy


Cookies Policy © Analytics Vidhya 2024.All rights reserved.

https://www.analyticsvidhya.com/blog/2020/07/read-and-update-google-spreadsheets-with-python/ 13/13

You might also like