Pygsheets: Google Spreadsheets Python API v4
Pygsheets is a simple, intuitive Python library that provides an interface to the Google Sheets API v4. It enables programmatic interaction with Google Spreadsheets, allowing users to create, open, edit, and share spreadsheets, as well as manage worksheets, cells, and ranges. The library supports advanced features like conditional formatting, data validation, and batch operations. The current version is 2.0.6, and it maintains an active development cycle with regular updates and bug fixes.
Warnings
- breaking Version 2.0.0 introduced significant breaking changes, including function renames and `authorize()` parameter changes.
- breaking In version 2.0.3, the internal handling of cell addressing was fundamentally changed, introducing `Address` and `GridRange` objects.
- breaking The default behavior of `get_as_df` changed in version 2.0.5.
- gotcha Authorization requires careful setup of a Google Cloud Project.
- gotcha When working with `Cell` objects, properties other than `value` are not fetched by default.
- deprecated The `link()` and `unlink()` methods on `Worksheet` objects are deprecated.
Install
-
pip install pygsheets
Imports
- pygsheets
import pygsheets
Quickstart
import pygsheets
import os
# Ensure your service account JSON key file is present and its path is in an environment variable
# Instructions to get one: https://pygsheets.readthedocs.io/en/latest/authorization.html#service-account
service_file_path = os.environ.get('PYGSHEETS_SERVICE_ACCOUNT_FILE', 'path/to/your/service_account.json')
if not os.path.exists(service_file_path) or service_file_path == 'path/to/your/service_account.json':
print(f"Warning: Service account file not found at '{service_file_path}'. Please set PYGSHEETS_SERVICE_ACCOUNT_FILE environment variable or update the path.")
print("Cannot run quickstart without valid service account credentials.")
else:
try:
# Authorize with service account credentials
gc = pygsheets.authorize(service_account_file=service_file_path)
# Open a spreadsheet by name or create it if it doesn't exist
spreadsheet_name = "My Test Spreadsheet"
try:
sh = gc.open(spreadsheet_name)
print(f"Opened existing spreadsheet: {spreadsheet_name}")
except pygsheets.exceptions.SpreadsheetNotFound:
sh = gc.create(spreadsheet_name)
# Share with your Google account if you want to see it in your Drive
# sh.share('your-email@example.com', role='writer', type='user')
print(f"Created new spreadsheet: {spreadsheet_name}")
# Select the first worksheet
wks = sh[0]
# Update a cell
wks.update_value('A1', 'Hello from pygsheets!')
print(f"Updated cell A1 in '{spreadsheet_name}' with 'Hello from pygsheets!'")
# Get a value
cell_value = wks.get_value('A1')
print(f"Value in A1: {cell_value}")
# Update a range of values
data = [[1, 2, 3], [4, 5, 6]]
wks.update_values('B2', data)
print(f"Updated range B2:D3 with: {data}")
except Exception as e:
print(f"An error occurred: {e}")