VOOZH about

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

⇱ How to Use Python to Automate Google Sheets? (2025 Edition)


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

How to Use Python to Automate Google Sheets? (2026 Edition)

Lakshay arora Last Updated : 06 Jan, 2026
8 min read

Automating tasks is a great way to save time and work more efficiently, especially for repetitive jobs. Python is a helpful tool for automating tasks in Google Sheets. This article will show you how to set up a Google service account, use Python to read and update data in Google Sheets, and analyze cricket data to find out how many runs each player scored. You’ll also learn about useful tools like gsspread and how to connect Python to Google Sheets. By the end, you’ll know how to use Python to automate Google Sheets. In this article, you will get to know all about to automate Google Sheets by using Python.

This article was published as a part of the Data Science Blogathon.

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.

  • 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.

πŸ‘ Create a Google Service Account
  • Then provide the project name and the organization name, which is optional. Then click on the create button.
  • Now that our project is created, we need to enable the APIs that we require in this project. Click on the Enable 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
  • Then, in the search bar, search for these APIs and click on the enable button.
  • 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.
  • 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.
  • 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 question, as we do not require any user data to run our application. And also, we are not using any cloud-based computing engine for our application. Finally, click on the β€˜What credentials do I need?’ button.
  • 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.

How to Read Data From Google Sheets Using Python?

We will read the commentary data of the India-Bangladesh cricket match. You can access the data (.csv) 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.

!pip3 install gspread
!pip3 install --upgrade google-api-python-client oauth2client

Python Code:

#!pip3 install gspread
#!pip3 install --upgrade google-api-python-client oauth2client

#importing the required libraries
import gspread
import pandas as pd
from oauth2client.service_account import ServiceAccountCredentials

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.

# define the scope
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']

# add credentials to the account
creds = ServiceAccountCredentials.from_json_keyfile_name('add_json_file_here.json', scope)

# authorize the clientsheet 
client = gspread.authorize(creds)

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.

# get the instance of the Spreadsheet
sheet = client.open('commentary data')

# get the first sheet of the Spreadsheet
sheet_instance = sheet.get_worksheet(0)

Basic functionalities

The API provides some basic functionalities, such as the number of columns by using col_count and get the value in a particular cell. Here are some examples of the same.

# get the total number of columns
sheet_instance.col_count
## >> 26


# get the value at the specific cell
sheet_instance.cell(col=3,row=2)
## >> <Cell R2C3 '63881'>

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.

# get all the records of the data
records_data = sheet_instance.get_all_records()

# view the data
records_data


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

# convert the json to dataframe
records_df = pd.DataFrame.from_dict(records_data)

# view the top records
records_df.head()
πŸ‘ google spreadsheets with python : Provide access to google sheet


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.

# number of runs by each batsman
runs = records_df.groupby(['Batsman_Name'])['Runs'].count().reset_index()
runs

Now, we will add this dataframe to google sheets.

Update Data in Google Sheets

The following are steps to update data in google sheets.

  • 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.
  • 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. Check the Values sheet in Github.

Conclusion

To summarize, in this article, we delved into understanding the various steps involved in the process of creating a service account. And how to read and write in Google Sheets right 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.

Hope you like the article and understand how to use Python to read Google Sheets. If you have any questions about Python in Google Sheets or how to read a Google Sheet in Python, feel free to ask!

In case you want to brush up on your spreadsheet concepts, I recommend the following article and course-

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

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.

Q2. What is the use of Google spreadsheet?

A. In Google spreadsheet, you can create and edit spreadsheets directly in your web browser, without the use of any specific software, and can be used in place of excel. Multiple people can work simultaneously, you can see people’s changes as they make them, and every change is saved automatically and can download csv files.

Q3. Can we do python programming and machine learning vscode?

A. Yes, we can do python programming in vscode and quickstart with python programming.

Q4. Can you do coding in Google Sheets?


Yes, you can code in Google Sheets using Google Apps Script. It lets you automate tasks and extend functionality using JavaScript.

Q5. Can we automate Google sheet?

You can automate Google Sheets using Google Apps Script, which is based on JavaScript. It allows you to create custom functions, automate tasks, format data, send emails, generate reports, and integrate with other Google services. Just open your Google Sheet, go to β€œExtensions” > β€œApps Script,” and start writing your scripts to automate tasks.

Ideas have always excited me. The fact that we could dream of something and bring it to reality fascinates me. Computer Science provides me a window to do exactly that. I love programming and use it to solve problems and a beginner in the field of Data Science.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

puneet wadhwa

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.

123 1
LAKSHAY ARORA

Hi Puneet, Please make sure that you have a copy of the spreadsheet on your google drive and the spreadsheet is shared with your Google service account.

123 456

Bro thankyou very much. It worked...

EMINA TUZOVIC

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. I made sure that I have a copy of the spreadsheet on my google drive and the spreadsheet is shared with my Google service account. but it still won't work.

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner