Afzal Badshah, PhD

Using Google Sheet API with Python

Here is the step-by-step guide to connecting Google Sheets to any Python program. In this tutorial, we connect it to Google Collab, but you can connect it to any application with the following the below points.

Requirement:

  1. A Google account A Google Cloud Platform (GCP) project (https://developers.google.com/workspace/guides/create-project)
  2. Python 3.x installed (https://www.python.org/downloads/)
  3. A code editor (e.g., Visual Studio Code, PyCharm,Google Colab)
Open google consle

1. Create a New Google Cloud Platform (GCP) Project

Google console library
Google sheets API

2. Enable Google Sheets API

To create service account
Service accounts
Creating new service account
Adding new key

3. Create a New Service Account

4. Download the JSON File

Program side:

Installed the required libraries

!pip install google-cloud
!pip install gspread

Upload the JSON file, which you downloaded from the google API to the working directory

Once you uploaded, write the following program to connect to the google sheet.

import gspread
from google.oauth2.service_account import Credentials
import pandas as pd

# Authenticate using the uploaded JSON file
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = Credentials.from_service_account_file('/content/your JSON file', scopes=scope)
gc = gspread.authorize(creds)

# Open the Google Sheet by its URL
sheet_url = 'your-url'
sheet = gc.open_by_url(sheet_url)

# Select the first worksheet
worksheet = sheet.get_worksheet(0)

# Read data from the worksheet into a Pandas DataFrame
data = worksheet.get_all_values()
df = pd.DataFrame(data[1:], columns=data[0])  # Assuming the first row contains column headers

# Display the DataFrame
print(df)

In the above program, replace the google sheet URL and json file names according to your project.

Output of the program

Exit mobile version