Package: pygsheets
pygsheets - Google Spreadsheets Python API v4A simple, intuitive library for google sheets which gets your work done.Features:Open, create, delete and share spreadsheets usingtitleorkeyIntuitive models - spreadsheet, worksheet, cell, datarangeControl permissions of spreadsheets.Set cell format, text format, color, write notesNamed and Protected Ranges SupportWork with range of cells easily with DataRange and GridrangeData validation support. checkboxes, drop-downs etc.Conditional formatting supportget multiple ranges with get_values_batch and update wit update_values_batchUpdatesversion2.0.6releasedInstallationFrom PyPi (Stable)pipinstallpygsheetsIf you are installing from pypi please see the docshere.From GitHub (Recommended)pipinstallhttps://github.com/nithinmurali/pygsheets/archive/staging.zipIf you are installing from github please see the docshere.Basic UsageBasic features are shown here, for complete set of features see the full documentationhere.Obtain OAuth2 credentials from Google Developers Console forgoogle spreadsheet apianddrive apiand save the file asclient_secret.jsonin same directory as project.read more here.Start using pygsheets:Sample scenario : you want to share a numpy array with your remote friendimportpygsheetsimportnumpyasnpgc=pygsheets.authorize()# Open spreadsheet and then worksheetsh=gc.open('my new sheet')wks=sh.sheet1# Update a cell with value (just to let him know values is updated ;) )wks.update_value('A1',"Hey yank this numpy array")my_nparray=np.random.randint(10,size=(3,4))# update the sheet with arraywks.update_values('A2',my_nparray.tolist())# share the sheet with your friendsh.share("myFriend@gmail.com")Sample Scenario: you want to fill height values of students## import pygsheets and open the sheet as given aboveheader=wks.cell('A1')header.value='Names'header.text_format['bold']=True# make the header boldheader.update()# or achive the same in onelinerwks.cell('B1').set_text_format('bold',True).value='heights'# set the nameswks.update_values('A2:A5',[['name1'],['name2'],['name3'],['name4']])# set the heightsheights=wks.range('B2:B5',returnas='range')# get the range as DataRange objectheights.name="heights"# name the rangeheights.update_values([[50],[60],[67],[66]])# update the valueswks.update_value('B6','=average(heights)')# set the avg value of heights using named rangeMore ExamplesOpening a Spreadsheet# You can open a spreadsheet by its title as it appears in Google Docssh=gc.open("pygsheetTest")# If you want to be specific, use a keysht1=gc.open_by_key('1mwA-NmvjDqd3A65c8hsxOpqdfdggPR0fgfg5nXRKScZAuM')# create a spreadsheet in a folder (by id)sht2=gc.create("new sheet",folder_name="my worksheets")# open enable TeamDrive supportgc.drive.enable_team_drive("Dqd3A65c8hsxOpqdfdggPR0fgfg")Operations on Spreadsheetdocshow codeimportpygsheetsc=pygsheets.authorize()sh=c.open('spreadsheet')# create a new sheet with 50 rows and 60 columswks=sh.add_worksheet("new sheet",rows=50,cols=60)# create a new sheet with 50 rows and 60 colums at the begin of worksheetswks=sh.add_worksheet("new sheet",rows=50,cols=60,index=0)# or copy from another worksheetwks=sh.add_worksheet("new sheet",src_worksheet='<other worksheet instance>')# delete this wroksheetsh.del_worksheet(wks)# unshare the sheetsh.remove_permissions("myNotSoFriend@gmail.com")Selecting a Worksheetshow codeimportpygsheetsc=pygsheets.authorize()sh=c.open('spreadsheet')# Select worksheet by id, index, title.wks=sh.worksheet_by_title("my test sheet")# By any propertywks=sh.worksheet('index',0)# Get a list of all worksheetswks_list=sh.worksheets()# Or justwks=sh[0]Operations on Worksheetdocshow code# Get values as 2d array('matrix') which can easily be converted to an numpy aray or as 'cell' listvalues_mat=wks.get_values(start=(1,1),end=(20,20),returnas='matrix')# Get values of - rows A1 to B10, column C, 1st row, 10th rowwks.get_values_batch(['A1:B10','C','1',(10,None)])# Get all values of sheet as 2d list of cellscell_matrix=wks.get_all_values(returnas='matrix')# update a range of values with a cell list or matrixwks.update_values(crange='A1:E10',values=values_mat)# update multiple ranges with bath updatewks.update_values_batch(['A1:A2','B1:B2'],[[[1],[2]],[[3],[4]]])# Insert 2 rows after 20th row and fill with valueswks.insert_rows(row=20,number=2,values=values_list)# resize by changing rows and columswks.rows=30# use the worksheet as a csvforrowinwks:print(row)# get values by indexesA1_value=wks[0][0]# clear all valueswks.clear()# Search for a table in the worksheet and append a row to itwks.append_table(values=[1,2,3,4])# export a worksheet as csvwks.export(pygsheets.ExportType.CSV)# Find/Replace cells with string valuecell_list=worksheet.find("query string")# Find/Replace cells with regexpfilter_re=re.compile(r'(small|big) house')cell_list=worksheet.find(filter_re,searchByRegex=True)cell_list=worksheet.replace(filter_re,'some house',searchByRegex=True)# Move a worksheet in the same spreadsheet (update index)wks.index=2# index start at 1 , not 0# Update titlewks.title="NewTitle"# Update hidden statewks.hidden=False# working with named rangeswks.create_named_range('A1','A10','prices')wks.get_named_range('prices')wks.get_named_ranges()# will return a list of DataRange objectswks.delete_named_range('prices')# apply formatwks.apply_format(['A1:B1','D:E'],["NUMBER","TEXT"])# Plot a chart/graphwks.add_chart(('A1','A6'),[('B1','B6')],'Health Trend')# create drop-downswks.set_data_validation(start='C4',end='E7',condition_type='NUMBER_BETWEEN',condition_values=[2,10],strict=True,inputMessage="inut between 2 and 10")# set a formula and extend it to more cellscell=wks.cell('C1')cell.value='=A1+B1'wks.apply_format('C1:C10',cell,'userEnteredValue.formulaValue')Pandas integrationIf you work with pandas, you can directly use the dataframes#set the values of a pandas dataframe to sheetwks.set_dataframe(df,(1,1))#you can also get the values of sheet as dataframedf=wks.get_as_df()Cell ObjectdocEach cell has avalueand cordinates (row,col,label) properties.Getting cell objectsshow codec1=Cell('A1',"hello")# create a unlinked cellc1=worksheet.cell('A1')# creates a linked cell whose changes syncs instantanouslycl.value# Getting cell valuec1.value_unformatted#Getting cell unformatted valuec1.formula# Getting cell formula if anyc1.note# any notes on the cellc1.address# address object with cell positioncell_list=worksheet.range('A1:C7')# get a range of cellscell_list=worksheet.col(5,returnas='cell')# return all cells in 5th column(E)Most of the functions hasreturnasparam, if whose value iscellit will return a list of cell objects. Also you can uselabelor(row,col)tuple interchangbly as a cell adressCell OperationsEach cell is directly linked with its cell in spreadsheet, hence changing the value of cell object will update the corresponding cell in spreadsheet unless you explictly unlink it
Also not that bu default only the value of cell is fetched, so if you are directly accessing any cell properties callcell.fetch()beforehand.Different ways of updating Cellsshow code# using linked cellsc1=worksheet.cell('B1')# created from worksheet, so linked cellc1.col=5# Now c1 correponds to E1c1.value="hoho"# will change the value of E1# Or onlinerworksheet.update_value('B1','hehe')# get a range of cellscell_list=worksheet.range('A1:C7')cell_list=worksheet.get_values(start='A1',end='C7',returnas='cells')cell_list=worksheet.get_row(2,returnas='cells')# add formulac1.formula='A1+C2'c1.formula# '=A1+C2'# get neighbouring cellsc2=c1.neighbour('topright')# you can also specify relative position as tuple eg (1,1)# set cell formatc1.set_number_format(pygsheets.FormatType.NUMBER,'00.0000')# write notes on cellc1.note="yo mom"# set cell colorc1.color=(1.0,1.0,1.0,1.0)# Red, Green, Blue, Alpha# set text formatc1.text_format['fontSize']=14c1.set_text_format('bold',True)# sync the changesc1.update()# you can unlink a cell and set all required properties and then link it# So yu could create a model cell and update multiple sheetsc.unlink()c.note="offine note"c.link(wks1,True)c.link(wks2,True)DataRange ObjectdocThe DataRange is used to represent a range of cells in a worksheet. They can be named or protected.
Almost allget_functions has areturnasparam, set it torangeto get a range object.show code# Getting a Range objectrng=wks.get_values('A1','C5',returnas='range')rng.start_addr='A'# make the range unbounded on rows <Datarange Sheet1!A:B>drange.end_addr=None# make the range unbounded on both axes <Datarange Sheet1># Named rangesrng.name='pricesRange'# will make this range a named rangerng=wks.get_named_ranges('commodityCount')# directly get a named rangerng.name=''# will delete this named range#Protected rangesrng.protected=Truerng.editors=('users','someemail@gmail.com')# Setting Format# first create a model cell with required propertiesmodel_cell=Cell('A1')model_cell.color=(1.0,0,1.0,1.0)# rose color cellmodel_cell.format=(pygsheets.FormatType.PERCENT,'')# Setting format to multiple cells in one gorng.apply_format(model_cell)# will make all cell in this range rose color and percent format# Or if you just want to apply format, you can skip fetching data while creating datarangeDatarange('A1','A10',worksheet=wks).apply_format(model_cell)# get cells in rangecell=rng[0][1]Batching callsIf you are calling a lot of spreadsheet modification functions (non value update). you can merge them into a single call.
By doing so all the requests will be merged into a single call.gc.set_batch_mode(True)wks.merge_cells("A1","A2")wks.merge_cells("B1","B2")Datarange("D1","D5",wks).apply_format(cell)gc.run_batch()# All the above requests are executed heregc.set_batch_mode(False)Batching also happens when you unlink worksheet. But in that case the requests are not merged.How to ContributeThis library is still in development phase.Follow theContributing to Open SourceGuide.Branch off of thestagingbranch, and submit Pull Requests back to
that branch.  Note that themasterbranch is used for version
bumps and hotfixes only.For quick testing the changes you have made to source, run the filetests/manual_testing.py. It will give you an IPython shell with lastest code loaded.Report Issues/FeaturesPlease report bugs and suggest features via theGitHub Issues.Before opening an issue, search the tracker for possible duplicates.If you have any usage questions, ask a question on stackoverflow withpygsheetsTagRun Testsinstallpip install -r requirements-dev.txtrunmake testNow that you have scrolled all the way down,finding this library useful?