Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
What Is Google Sheets and How to use it?
Next article icon

How to Automate Google Sheets with Python?

Last Updated : 28 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will discuss how to Automate Google Sheets with Python.

Pygsheets is a simple python library that can be used to automate Google Sheets through the Google Sheets API. An example use of this library would be to automate the plotting of graphs based on some data in CSV files that we can export to Google Sheets. So, let’s proceed further.

How do pygsheets work with Google Sheets?

  • The Client creates and accesses spreadsheets.
  • The spreadsheet is the class used to represent a Google Sheet.
  • Each spreadsheet has multiple ‘Worksheets’.
  • The data inside the worksheets can be accessed through ‘Cell’ objects which supports formatting, formulas, etc.

Step 1: Enable APIs for Google Sheets and Google Drive

A.  Go to Google Developers Console and create a new project. 

B. Enter a name for the project. You may leave ‘Location’ as ‘No Organization’. Press Create.

C. Now, we will enable the Google Sheets and Google Drive APIs. To do so, click on ‘ENABLE APIS AND SERVICES’. 

D. Now enter ‘Google Sheets API’ in the search bar, click on the ‘Google Sheets API’ option, and press ‘ENABLE’.

E. Similarly, search for and enable the ‘Google Drive API’.

Step 2: Create a Service Account and fetch credentials

The Service Account is what we will be using to make our API calls to edit the spreadsheets. It is associated with the email id of the Google Developers Account that we used to create our project with.

A. To create one, click on ‘CREATE CREDENTIALS’.

B. Select ‘Google Sheets API’ in the ‘Select an API’ section, ‘Application Data’ and ‘No, I’m not using them’ in the following questions. Click ‘NEXT’.

C. Enter the display name and name for the service account.

D. Now we will enter the access level for the service account. Click on ‘Select a Role’ and select ‘Editor’ under the ‘basic’ section. Press ‘CONTINUE’.

E. You may leave the ‘Grant users access to this service account’ section as blank and now, press ‘DONE’.

F. Now click on the service account that was just created.

G. Go to the ‘KEYS’ section and click on ‘ADD KEY’. Select ‘Create new key’.

H. Select ‘JSON’ to download the keys in the JSON file format. Click on ‘CREATE’.

I. The above file will be downloaded into your system. Do not share the keys with anyone and keep them safe. Place the file in the folder in which you want to create your python project.

Step 3: Add Service Account as an editor

Create a new Google Sheet in your Google account, or you can even use an existing one. Simply add the service account as one of the editors in that sheet. You will find the Service Account email in your keys file as “client_email”.

Step 4: Authorize pygsheets 

A. Now create a main.py file and place it in the same folder as your Keys file.

B. Install Required Library.

pip install pygsheets

C. Now, write the following code in the main.py file to verify the successful authorization of pygsheets.

Python3

# Importing required library
import pygsheets
  
# Create the Client
# Enter the name of the downloaded KEYS 
# file in service_account_file
client = pygsheets.authorize(service_account_file="gfg-pygsheets-demo-e3d0c0e482af.json")
  
# Sample command to verify successful
# authorization of pygsheets
# Prints the names of the spreadsheet
# shared with or owned by the service 
# account
print(client.spreadsheet_titles())
                      
                       

The above code should print the name of the spreadsheet that we shared with the service account in step 3. Hence, we have successfully linked our Google Sheet with the Service Account and now, we will use the Client to edit the spreadsheet.

Step 5: Editing the spreadsheet

A. Now, we will look at some commands to edit our spreadsheet through Python code.

Python3

# Importing required library
import pygsheets
  
# Create the Client
client = pygsheets.authorize(service_account_file="gfg-pygsheets-demo-e3d0c0e482af.json")
  
# opens a spreadsheet by its name/title
spreadsht = client.open("gfg-demo-sheet")
  
# opens a worksheet by its name/title
worksht = spreadsht.worksheet("title", "Sheet1")
  
# Now, let's add data to our worksheet
  
# Creating the first column
worksht.cell("A1").set_text_format("bold", True).value = "Item"
  
# if updating multiple values, the data
# should be in a matrix format
worksht.update_values("A2:A6", [["Pencil"], ["Eraser"], 
                                ["Sharpener"], ["Ruler"], 
                                ["Pen"]])  # Adding row values
  
# Similarly, creating the second column
worksht.cell("B1").set_text_format("bold", True).value = "Price"
worksht.update_values("B2:B6", [[5], [3], [5], [15], [10]])
  
# Creating a basic bar chart
worksht.add_chart(("A2", "A6"), [("B2", "B6")], "Shop")
                      
                       

Output:



Next Article
What Is Google Sheets and How to use it?

S

sejalabrol
Improve
Article Tags :
  • Geeks Premier League
  • Python
  • Geeks-Premier-League-2022
  • python-utility
Practice Tags :
  • python

Similar Reads

  • How to Automate an Excel Sheet in Python?
    Before you read this article and learn automation in Python....let's watch a video of Christian Genco (a talented programmer and an entrepreneur) explaining the importance of coding by taking the example of automation. You might have laughed loudly after watching this video and you surely, you might
    8 min read
  • Using Google Sheets as Database in Python
    In this article we'll be discussing how we can use Google Sheets to run like a database for any Python file.  Google Spreadsheets:Google Spreadsheets is free online web based application that resembles Microsoft Excel. You can use it to create and edit tables for various projects such as Contact Lis
    4 min read
  • How to Use Google Cloud Function with Python ?
    Google Cloud Functions provides a way to run small pieces of code in response to cloud events without managing servers. If you're a developer looking to automate tasks, process data or build APIs, Python is a great language for working with Google Cloud Functions. In this article, we will look into
    6 min read
  • What Is Google Sheets and How to use it?
    Google Sheets designed as part of Google Workspace (formerly G Suite), Google Sheets works seamlessly online, enabling users to manage data, perform calculations, and visualize information through charts and graphs. It is a popular alternative to Microsoft Excel, offering accessibility across device
    5 min read
  • Store Google Sheets data into SQLite Database using Python
    In this article, we are going to store google sheets data into a database using python. The first step is to enable the API and to create the credentials, so let's get stared. Enabling the APIs and creating the credentialsGo to Marketplace in Cloud Console.Click on ENABLE APIS AND SERVICESThen Searc
    5 min read
  • What is Google Sheets API and How to Use it?
    We all are familiar with spreadsheets and worked with them since we first learned about computers. We are used to arranging our data in a tabular manner in the form of rows and columns. When we are working on a project and wish to save our data in a tabular form, we think of relational databases. In
    8 min read
  • How to automate system administration with Python
    Python has become one of the most popular programming languages for system administrators due to its simplicity, flexibility, and extensive support for various system management tasks. Whether you're automating repetitive tasks, managing files and directories, or handling user permissions, Python pr
    5 min read
  • Google Maps Selenium automation using Python
    Prerequisites: Browser Automation using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS, and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can
    4 min read
  • How to Use Google Sheets as a Database
    Google Sheets emerges as a versatile tool that goes beyond its conventional spreadsheet capabilities. While traditionally used for creating budgets, charts, and tables, Google Sheets as a database provides an accessible and collaborative platform for storing and manipulating data. In this guide, we’
    10 min read
  • How to Open a CSV File in Google Sheets
    Ever received a data dump in a mysterious file format called CSV? Don't worry, it's not an alien language! CSV stands for "Comma-Separated Values," and it's a common way to store data in rows and columns. But how do you unlock this treasure trove of information? Fear not, data warrior! This guide wi
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences