Update existing google sheet with a pandas data frame and gspread

Mark Gilliland picture Mark Gilliland · Mar 14, 2017 · Viewed 8.5k times · Source

I would like to update a particular tab in a Google Sheets document using a pandas data frame. I have reviewed the documentation on GitHub and readthedocs.io and am able to successfully update a certain range of cells using the following code:

cell_list = sheet4.range('A1:A7')
cell_values = [1,2,3,4,5,6,7]

for i, val in enumerate(cell_values):  
    cell_list[i].value = val    

sheet4.update_cells(cell_list)

As a beginner, I am having trouble connecting the dots and figuring out how to update the entire sheet using a Pandas data frame. The data frame will have 9 columns and up to 9,000 rows, with the number of rows varying depending on when the data frame is generated.

Any advice is appreciated.

Answer

Nithin picture Nithin · Jul 2, 2017

pygsheets have pandas support inbuild.

import pygsheets
gc = pygsheets.authorize(service_file='file.json')

#open the google spreadsheet 
sh = gc.open_by_url('url')

#select the first sheet 
wks = sh[0]

#update the first sheet with df, starting at cell B2. 
wks.set_dataframe(df, 'B2')