pygsheets - Google Spreadsheets Python API v4
A simple, intuitive library for google sheets which gets your work done.
Features:
- Open, create, delete and share spreadsheets using title or key
- Intuitive models - spreadsheet, worksheet, cell, datarange
- Control permissions of spreadsheets.
- Set cell format, text format, color, write notes
- Named and Protected Ranges Support
- Work with range of cells easily with DataRange and Gridrange
- Data validation support. checkboxes, drop-downs etc.
- Conditional formatting support
- get multiple ranges with get_values_batch and update wit update_values_batch
Updates
Installation
From PyPi (Stable)
pip install pygsheets
If you are installing from pypi please see the docs here.
From GitHub (Recommended)
pip install https://github.com/nithinmurali/pygsheets/archive/staging.zip
If you are installing from github please see the docs here.
Basic Usage
Basic features are shown here, for complete set of features see the full documentation here.
-
Obtain OAuth2 credentials from Google Developers Console for google spreadsheet api and drive api and save the file as client_secret.json
in same directory as project. read more here.
-
Start using pygsheets:
Sample scenario : you want to share a numpy array with your remote friend
import pygsheets
import numpy as np
gc = pygsheets.authorize()
sh = gc.open('my new sheet')
wks = sh.sheet1
wks.update_value('A1', "Hey yank this numpy array")
my_nparray = np.random.randint(10, size=(3, 4))
wks.update_values('A2', my_nparray.tolist())
sh.share("myFriend@gmail.com")
Sample Scenario: you want to fill height values of students
header = wks.cell('A1')
header.value = 'Names'
header.text_format['bold'] = True
header.update()
wks.cell('B1').set_text_format('bold', True).value = 'heights'
wks.update_values('A2:A5',[['name1'],['name2'],['name3'],['name4']])
heights = wks.range('B2:B5', returnas='range')
heights.name = "heights"
heights.update_values([[50],[60],[67],[66]])
wks.update_value('B6','=average(heights)')
More Examples
Opening a Spreadsheet
sh = gc.open("pygsheetTest")
sht1 = gc.open_by_key('1mwA-NmvjDqd3A65c8hsxOpqdfdggPR0fgfg5nXRKScZAuM')
sht2 = gc.create("new sheet", folder_name="my worksheets")
gc.drive.enable_team_drive("Dqd3A65c8hsxOpqdfdggPR0fgfg")
Operations on Spreadsheet doc
show code
import pygsheets
c = pygsheets.authorize()
sh = c.open('spreadsheet')
wks = sh.add_worksheet("new sheet",rows=50,cols=60)
wks = sh.add_worksheet("new sheet",rows=50,cols=60,index=0)
wks = sh.add_worksheet("new sheet", src_worksheet='<other worksheet instance>')
sh.del_worksheet(wks)
sh.remove_permissions("myNotSoFriend@gmail.com")
Selecting a Worksheet
show code
import pygsheets
c = pygsheets.authorize()
sh = c.open('spreadsheet')
wks = sh.worksheet_by_title("my test sheet")
wks = sh.worksheet('index', 0)
wks_list = sh.worksheets()
wks = sh[0]
Operations on Worksheet doc
show code
values_mat = wks.get_values(start=(1,1), end=(20,20), returnas='matrix')
wks.get_values_batch(['A1:B10', 'C', '1', (10, None)])
cell_matrix = wks.get_all_values(returnas='matrix')
wks.update_values(crange='A1:E10', values=values_mat)
wks.update_values_batch(['A1:A2', 'B1:B2'], [[[1],[2]], [[3],[4]]])
wks.insert_rows(row=20, number=2, values=values_list)
wks.rows=30
for row in wks:
print(row)
A1_value = wks[0][0]
wks.clear()
wks.append_table(values=[1,2,3,4])
wks.export(pygsheets.ExportType.CSV)
cell_list = worksheet.find("query string")
filter_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)
wks.index = 2
wks.title = "NewTitle"
wks.hidden = False
wks.create_named_range('A1', 'A10', 'prices')
wks.get_named_range('prices')
wks.get_named_ranges()
wks.delete_named_range('prices')
wks.apply_format(['A1:B1', 'D:E'], ["NUMBER", "TEXT"])
wks.add_chart(('A1', 'A6'), [('B1', 'B6')], 'Health Trend')
wks.set_data_validation(start='C4', end='E7', condition_type='NUMBER_BETWEEN', condition_values=[2,10], strict=True, inputMessage="inut between 2 and 10")
cell = wks.cell('C1')
cell.value = '=A1+B1'
wks.apply_format('C1:C10', cell, 'userEnteredValue.formulaValue')
Pandas integration
If you work with pandas, you can directly use the dataframes
wks.set_dataframe(df,(1,1))
df = wks.get_as_df()
Cell Object doc
Each cell has a value and cordinates (row, col, label) properties.
Getting cell objects
show code
c1 = Cell('A1',"hello")
c1 = worksheet.cell('A1')
cl.value
c1.value_unformatted
c1.formula
c1.note
c1.address
cell_list = worksheet.range('A1:C7')
cell_list = worksheet.col(5, returnas='cell')
Most of the functions has returnas
param, if whose value is cell
it will return a list of cell objects. Also you can use label or (row,col) tuple interchangbly as a cell adress
Cell Operations
Each 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 call cell.fetch()
beforehand.
Different ways of updating Cells
show code
c1 = worksheet.cell('B1')
c1.col = 5
c1.value = "hoho"
worksheet.update_value('B1', 'hehe')
cell_list = worksheet.range('A1:C7')
cell_list = worksheet.get_values(start='A1', end='C7', returnas='cells')
cell_list = worksheet.get_row(2, returnas='cells')
c1.formula = 'A1+C2'
c1.formula
c2 = c1.neighbour('topright')
c1.set_number_format(pygsheets.FormatType.NUMBER, '00.0000')
c1.note = "yo mom"
c1.color = (1.0, 1.0, 1.0, 1.0)
c1.text_format['fontSize'] = 14
c1.set_text_format('bold', True)
c1.update()
c.unlink()
c.note = "offine note"
c.link(wks1, True)
c.link(wks2, True)
DataRange Object doc
The DataRange is used to represent a range of cells in a worksheet. They can be named or protected.
Almost all get_
functions has a returnas
param, set it to range
to get a range object.
show code
rng = wks.get_values('A1', 'C5', returnas='range')
rng.start_addr = 'A'
drange.end_addr = None
rng.name = 'pricesRange'
rng = wks.get_named_ranges('commodityCount')
rng.name = ''
rng.protected = True
rng.editors = ('users', 'someemail@gmail.com')
model_cell = Cell('A1')
model_cell.color = (1.0,0,1.0,1.0)
model_cell.format = (pygsheets.FormatType.PERCENT, '')
rng.apply_format(model_cell)
Datarange('A1','A10', worksheet=wks).apply_format(model_cell)
cell = rng[0][1]
Batching calls
If 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()
gc.set_batch_mode(False)
Batching also happens when you unlink worksheet. But in that case the requests are not merged.
How to Contribute
This library is still in development phase.
- Follow the Contributing to Open Source Guide.
- Branch off of the
staging
branch, and submit Pull Requests back to
that branch. Note that the master
branch is used for version
bumps and hotfixes only. - For quick testing the changes you have made to source, run the file
tests/manual_testing.py
. It will give you an IPython shell with lastest code loaded.
Report Issues/Features
- Please report bugs and suggest features via the GitHub Issues.
- Before opening an issue, search the tracker for possible duplicates.
- If you have any usage questions, ask a question on stackoverflow with
pygsheets
Tag
Run Tests
- install
pip install -r requirements-dev.txt
- run
make test
Now that you have scrolled all the way down, finding this library useful?