gspread-formatting

1.2.1 · active · verified Sun Apr 12

gspread-formatting provides complete Google Sheets formatting support for gspread worksheets, allowing programmatic control over cell styles, conditional formatting, data validation, and more. The current version is 1.2.1. Releases occur periodically to add new features, fix bugs, and maintain compatibility with the underlying gspread library and Google Sheets API.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a gspread client (required for gspread-formatting), create or open a spreadsheet, define a custom `CellFormat` object, and apply it to a specific cell range using `format_cell_range`.

import gspread
from gspread_formatting import format_cell_range, CellFormat, Color
import os

# --- gspread client setup (outside gspread-formatting scope) ---
# Replace with your actual service account file path or other authentication method
SERVICE_ACCOUNT_FILE = os.environ.get('GSPREAD_SERVICE_ACCOUNT_FILE', 'path/to/your/service_account.json')

try:
    # Initialize gspread client (service account recommended for automation)
    gc = gspread.service_account(filename=SERVICE_ACCOUNT_FILE)
except Exception as e:
    print(f"Error initializing gspread client: {e}")
    print("Please ensure GSPREAD_SERVICE_ACCOUNT_FILE environment variable is set or path is correct.")
    exit(1)

# Open a sheet
try:
    spreadsheet = gc.open('My Formatted Sheet')
except gspread.exceptions.SpreadsheetNotFound:
    spreadsheet = gc.create('My Formatted Sheet')
    print(f"Created new spreadsheet: {spreadsheet.url}")

worksheet = spreadsheet.sheet1

# --- gspread-formatting usage ---

# Define a cell format
cell_format = CellFormat(
    backgroundColor=Color(1, 0.9, 0.9), # Light red background
    textFormat=CellFormat.textFormat(
        bold=True,
        foregroundColor=Color(1, 0, 0)
    )
)

# Apply the format to a range of cells (e.g., A1:C5)
format_cell_range(worksheet, 'A1:C5', cell_format)

print("Formatted cells A1:C5 with a light red background and bold red text.")
print("Check your spreadsheet to see the changes.")

view raw JSON →