Rob Weyant bio photo

Rob Weyant

Data Scientist at Powerley

Twitter LinkedIn Instagram Github Last.fm

gspread is a package by Anton Burnashev offers a simple interface between Python and Google Spreadsheet’s API.

Installation

# From PyPi
pip install gspread

Authorization

Google Spreadsheet’s API uses OAuth2 to handle authorization. You’ll need to generate an API Key. You can also use email/password to login with gspread.login(email,password).

import gspread
import json

oauthfile = '/path/to/file/your-api-key.json',                  
scope = ['https://spreadsheets.google.com/feeds']
json_key = json.load(open(oauthfile))
credentials = SignedJwtAssertionCredentials(json_key['client_email'], json_key['private_key'], scope)

# Authorize
gspreadclient = gspread.authorize(credentials)

Accessing Data

# Load spreadsheet
spreadsheet = gspreadclient.open('your spreadsheet')

# Load worksheet
worksheet = spreadsheet.worksheet('your worksheet')

# Get all values
dat = worksheet.get_all_values()

The gspread.Worksheet.get_all_values() returns a list of lists which is easily converted to NumPy format or just indexing normally. You can also get a specific row with gspread.Worksheet.row_values() and a specific cell with gspread.Worksheet.cell().

Updating Cells

# Insert 'abc' into the cell at the first row, first column.
worksheet.update_cell(1,1,'abc')

There are other functions to update the data, mainly gspread.Worksheet.append_row(). You can also change the size of the worksheet with gspread.Worksheet.add_rows(),gspread.Worksheet.add_cols(), gspread.Worksheet.resize().

More Resources