How to Export Data to Google Sheets from Python

Cody Schneider8 min read

Sending data from a Python script directly into a Google Sheet can automate your reporting and save you hours of copying and pasting. It transforms Google Sheets from a manual tool into a dynamic, updating dashboard for your app's data, marketing reports, or any other project. This article will walk you through the entire process, from setting up your Google credentials to writing data using the most popular Python libraries.

Before You Begin: Setting Up Your Google Cloud Project

Before writing a single line of Python, you need to authorize your script to interact with your Google account. This is the most complex part of the process, but if you follow these steps carefully, you’ll only need to do it once.

You’ll be using a "Service Account," which is like giving a robot its own special credentials to access your Google services without needing your personal username and password.

1. Create a New Project in the Google Cloud Console

First, head over to the Google Cloud Console. If you don't have a project already, you'll be prompted to create one. Give it a descriptive name like "Python Sheets Exporter" so you'll remember what it's for later.

2. Enable the Google Sheets and Google Drive APIs

Your new project doesn’t have permission to do anything yet. You need to explicitly enable the specific APIs your script will use.

  • In the console's search bar at the top, type "Google Drive API" and select it. Click the "Enable" button. (We need this to see and access our spreadsheets).
  • Do the same for the "Google Sheets API." Search for it, select it, and click "Enable." (This one allows us to actually read and write data to the cells).

3. Create a Service Account Credential

Now, let's create the special account for our Python script.

  1. Navigate to the "Credentials" page. You can find this in the left-hand navigation menu under "APIs & Services" > "Credentials."
  2. Click "+ Create Credentials" at the top and select "Service account."
  3. Give your service account a name (e.g., "python-sheets-bot") and a description. The "Service account ID" will be auto-generated. Click "Create and Continue."
  4. For "Grant this service account access to project," you can just add the "Editor" role for simplicity. Click "Continue."
  5. Skip the last step ("Grant users access to this service account") and click "Done."

4. Download Your JSON Key File

You now have a service account, but your script needs a "key" to prove its identity.

  • On the Credentials screen, find the service account you just created and click on it.
  • Go to the "KEYS" tab.
  • Click "Add Key" and then "Create new key."
  • Choose "JSON" as the key type and click "Create."

A JSON file will immediately download to your computer. Treat this file like a password! Anyone with this file can access your Google Sheets. Store it securely in your project folder and don't commit it to a public GitHub repository. For this tutorial, you can rename it to credentials.json for simplicity.

5. Share Your Google Sheet with the Service Account

Your service account now has a Google identity, but it can't see any of your files yet. The final setup step is to share the specific Google Sheet you want to write to, just like you would with a human coworker.

  • Open your downloaded credentials.json file in a text editor.
  • Find the line with the key "client_email". The value will look something like "python-sheets-bot@your-project-name.iam.gserviceaccount.com".
  • Copy that entire email address.
  • Open your Google Sheet, click the "Share" button in the top right, and paste that email address into the sharing dialog. Grant it "Editor" access.

With that done, all the Google configuration is handled. Now for the fun part: Python.

Step-by-Step Guide: Writing to Google Sheets with Python

We’ll use two fantastic Python libraries to make this process easy: gspread for interacting with the Google Sheets API and pandas for structuring our data. Pandas isn't strictly necessary, but it's the standard for data manipulation in Python, and transferring data from a pandas DataFrame is a very common workflow.

Step 1: Install a Few Libraries

If you don't have them installed already, open your terminal or command prompt and run the following command:

pip install gspread pandas google-auth-oauthlib

Step 2: Authenticate and Connect to Your Sheet

Create a Python file (e.g., sheet_exporter.py) in the same folder where you saved your credentials.json file. The first part of the script is about establishing a connection.

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

# Define the scope of the APIs we need to access.
scopes = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive"
]

# Load credentials from the JSON file
# Place your `credentials.json` in the same directory as this script
try:
    creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
    client = gspread.authorize(creds)
except FileNotFoundError:
    print("Error: credentials.json not found. Make sure the file is in the correct directory.")
    exit()
except Exception as e:
    print(f"An error occurred during authentication: {e}")
    exit()

# Open the spreadsheet by its name
try:
    spreadsheet = client.open("Your Spreadsheet Name Here")  # <-- IMPORTANT: Change this!
    worksheet = spreadsheet.worksheet("Sheet1")  # Or select by opening the first sheet: spreadsheet.sheet1
    print("Successfully connected to the spreadsheet.")
except gspread.exceptions.SpreadsheetNotFound:
    print("Error: Spreadsheet not found. Check the name and sharing permissions.")
    exit()

Make sure to replace "Your Spreadsheet Name Here" with the exact name of your Google Sheet. When you run this script, it should print "Successfully connected to the spreadsheet." If you get an error, double-check that you shared the sheet correctly with the service account's email.

Step 3: Prepare Your Data with Pandas

For this example, let's create a simple pandas DataFrame that simulates marketing campaign performance data. In a real-world scenario, you might be loading this data from a database, another file, or an API.

# This part goes after the connection code in your script

print("Preparing data...")

# Create a sample DataFrame
data = {
    'Date': ['2023-11-01', '2023-11-01', '2023-11-02', '2023-11-02'],
    'Campaign': ['Facebook Ads - US', 'Google Ads - US', 'Facebook Ads - US', 'Email Campaign'],
    'Spend': [150.75, 220.50, 165.25, 25.00],
    'Conversions': [12, 18, 15, 7]
}
df = pd.DataFrame(data)

print("Sample DataFrame created:")
print(df)

Step 4: Send the DataFrame to Google Sheets

Now for the payoff. With our data ready in a DataFrame and our connection established, sending it to the sheet is incredibly simple. We'll first clear the sheet to make sure we're not just adding data to what's already there, and then we'll write our new data.

The worksheet.update() method in gspread expects a list of lists, where each inner list is a row. A common pattern is to combine the DataFrame's column headers with its values.

# ... add this at the end of your script

print("\nClearing previous data from worksheet...")
worksheet.clear() 

print("Writing data to worksheet...")

# Convert DataFrame to a list of lists, including headers
data_to_write = [df.columns.values.tolist()] + df.values.tolist()

# Write the data to the sheet
worksheet.update(data_to_write, 'A1')

print("Data successfully written to Google Sheets!")

We specify 'A1' to tell gspread where to start pasting the data. Go check your Google Sheet - it should be populated with your data, perfectly formatted in rows and columns!

Putting It All Together: The Complete Script

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

# --- 1. SETUP AND AUTHENTICATION ---
scopes = [
    "https://www.googleapis.com/auth/spreadsheets",
    "https://www.googleapis.com/auth/drive"
]

try:
    creds = Credentials.from_service_account_file("credentials.json", scopes=scopes)
    client = gspread.authorize(creds)
except FileNotFoundError:
    print("Error: credentials.json not found. Make sure the file is in the correct directory.")
    exit()
except Exception as e:
    print(f"An error occurred during authentication: {e}")
    exit()

# Open the spreadsheet and worksheet
try:
    spreadsheet = client.open("Your Spreadsheet Name Here")  # <-- IMPORTANT: Change this!
    worksheet = spreadsheet.worksheet("Sheet1")
    print("Successfully connected to the spreadsheet.")
except gspread.exceptions.SpreadsheetNotFound:
    print("Error: Spreadsheet not found. Check the name and sharing permissions.")
    exit()

# --- 2. PREPARE THE DATA with Pandas ---
print("Preparing data...")
data = {
    'Date': ['2023-11-01', '2023-11-01', '2023-11-02', '2023-11-02'],
    'Campaign': ['Facebook Ads - US', 'Google Ads - US', 'Facebook Ads - US', 'Email Campaign'],
    'Spend': [150.75, 220.50, 165.25, 25.00],
    'Conversions': [12, 18, 15, 7]
}
df = pd.DataFrame(data)
print("Sample DataFrame created:")
print(df)

# --- 3. EXPORT THE DATA TO GOOGLE SHEETS ---
print("\nClearing previous data from worksheet...")
worksheet.clear() 

print("Writing data to worksheet...")
# Write headers
worksheet.update([df.columns.values.tolist()], 'A1')
# Write data
worksheet.update(df.values.tolist(), 'A2')

print("Data successfully written to Google Sheets!")

Final Thoughts

Automating data transfers into Google Sheets using Python is a powerful skill. Once you get through the initial configuration in the Google Cloud Console, the actual process of exporting data becomes remarkably simple with libraries like gspread and pandas. This opens the door to creating automated reports, quick data dashboards, and logging systems at no cost.

While DIY Python scripts are great for specific exports, we've found that marketing and sales teams often need to connect and analyze data from dozens of different platforms in one place - without writing any code. That’s why we built Graphed. It connects directly to all your data sources like Google Analytics, Shopify, Facebook Ads, and Salesforce. Instead of programming scripts, you just ask questions in plain English to build real-time, interactive dashboards instantly. It automates away the entire manual reporting process so you can focus on insights instead of configuration.

Related Articles

How to Connect Facebook to Google Data Studio: The Complete Guide for 2026

Connecting Facebook Ads to Google Data Studio (now called Looker Studio) has become essential for digital marketers who want to create comprehensive, visually appealing reports that go beyond the basic analytics provided by Facebook's native Ads Manager. If you're struggling with fragmented reporting across multiple platforms or spending too much time manually exporting data, this guide will show you exactly how to streamline your Facebook advertising analytics.

Appsflyer vs Mixpanel​: Complete 2026 Comparison Guide

The difference between AppsFlyer and Mixpanel isn't just about features—it's about understanding two fundamentally different approaches to data that can make or break your growth strategy. One tracks how users find you, the other reveals what they do once they arrive. Most companies need insights from both worlds, but knowing where to start can save you months of implementation headaches and thousands in wasted budget.