This blog article shows you one of the possible methods to write data into Google Sheet.
1. You go to Google API Console to enable Google Sheet API.
2. Create a KEY then download the Json file for the KEY, you realize I have this like in my code later.
creds = ServiceAccountCredentials.from_json_keyfile_name(‘myprojectiscc-e22bd9284a10.json’, scope)
3. Share the Google Sheet with the Service Account
- Open your Google Sheet.
- Click the Share button.
- Add the service account email (found in the JSON key file under client_email) as an Editor or Viewer.
- Example service account email: your-service-account@your-project.iam.gserviceaccount.com.
Also: Where to get the ClientId and ClientSecret for Google API
You can then use the code snippet below to test writing to Google Sheet.
import pandas as pd
import gspread
from oauth2client.service_account import ServiceAccountCredentials
# Define the scope
scope = [“https://spreadsheets.google.com/feeds”, “https://www.googleapis.com/auth/drive”, ‘https://www.googleapis.com/auth/spreadsheets’%5D
# Add credentials to the account
creds = ServiceAccountCredentials.from_json_keyfile_name(‘myprojectiscc-e22bd9284a10.json’, scope)
# Authorize the clientsheet
client = gspread.authorize(creds)
# Get the instance of the Spreadsheet
sheet = client.open_by_url(“https://docs.google.com/spreadsheets/d/130Npclfy9nPsXRihiczaUmW6-hza21bwfGfVa064sDo/edit”)
# Get the first sheet of the Spreadsheet
worksheet = sheet.get_worksheet(0)
# Read CSV file into DataFrame
df = pd.read_csv(‘data.csv’)
# Write DataFrame to Google Sheet
worksheet.update([df.columns.values.tolist()] + df.values.tolist())
Source code download: https://github.com/chanmmn/python/tree/main/2025/WriteGoogleSheet?WT.mc_id=DP-MVP-36769
Reference: https://docs.gspread.org/en/v6.1.3/?WT.mc_id=DP-MVP-36769
Pingback: Python in Ubuntu | Chanmingman's Blog
Pingback: Read Top 100 rows from CSV File Python | Chanmingman's Blog