gspread-pandas

3.3.0 · active · verified Tue Apr 14

gspread-pandas is a Python package that simplifies interaction between Pandas DataFrames and Google Spreadsheets. It leverages the `gspread` library for underlying API communication and adds extensive functionality for handling DataFrame-specific operations, multi-level headers, merged cells, and authentication. The library is actively maintained with regular updates and releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate, open/create a Google Spreadsheet, write a Pandas DataFrame to a specified worksheet, and then read it back. Proper authentication (e.g., setting up a service account JSON file in `~/.config/gspread_pandas/google_secret.json` and sharing your spreadsheet with the service account email) is a prerequisite for running this code.

import pandas as pd
import os
from gspread_pandas import Spread

# IMPORTANT: Ensure your Google client credentials (e.g., service account JSON)
# are set up at ~/.config/gspread_pandas/google_secret.json or via environment variables.
# See documentation for detailed authentication setup.

# Replace with your actual spreadsheet name, or fetch from environment
spreadsheet_name = os.environ.get('GSPREAD_PANDAS_SHEET_NAME', 'My Example Spreadsheet')

# Create a dummy DataFrame to write to the spreadsheet
data = {'col1': [1, 2, 3], 'col2': ['A', 'B', 'C']}
df_to_write = pd.DataFrame(data)

try:
    # Open the spreadsheet (or create if it doesn't exist and create_spread=True)
    # By default, it looks for ~/.config/gspread_pandas/google_secret.json
    spread = Spread(spreadsheet_name, create_spread=True)
    
    # Get a list of existing worksheets
    print(f"Worksheets in '{spreadsheet_name}': {spread.sheets}")

    # Write DataFrame to a new worksheet or an existing one
    # Using 'overwrite=True' to clear existing data, 'sheet=' to specify sheet name
    sheet_name = 'DataFrame Data'
    print(f"Writing DataFrame to sheet: '{sheet_name}'")
    spread.df_to_sheet(df_to_write, sheet=sheet_name, index=False, overwrite=True)
    
    # Read data back into a DataFrame
    df_from_sheet = spread.sheet_to_df(sheet=sheet_name)
    print(f"\nData read from '{sheet_name}':")
    print(df_from_sheet.head())

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your Google API credentials are correctly configured and the spreadsheet exists/is accessible.")

view raw JSON →