Giter VIP home page Giter VIP logo

gspread's Introduction

Google Spreadsheets Python API v4

main workflow GitHub licence GitHub downloads documentation PyPi download PyPi version python version

Simple interface for working with Google Sheets.

Features:

  • Open a spreadsheet by title, key or URL.
  • Read, write, and format cell ranges.
  • Sharing and access control.
  • Batching updates.

Installation

pip install gspread

Requirements: Python 3.8+.

Basic Usage

  1. Create credentials in Google API Console

  2. Start using gspread

import gspread

gc = gspread.service_account()

# Open a sheet from a spreadsheet in one go
wks = gc.open("Where is the money Lebowski?").sheet1

# Update a range of cells using the top left corner address
wks.update([[1, 2], [3, 4]], "A1")

# Or update a single cell
wks.update_acell("B42", "it's down there somewhere, let me take another look.")

# Format the header
wks.format('A1:B1', {'textFormat': {'bold': True}})

v5.12 to v6.0 Migration Guide

Upgrade from Python 3.7

Python 3.7 is end-of-life. gspread v6 requires a minimum of Python 3.8.

Change Worksheet.update arguments

The first two arguments (values & range_name) have swapped (to range_name & values). Either swap them (works in v6 only), or use named arguments (works in v5 & v6).

As well, values can no longer be a list, and must be a 2D array.

- file.sheet1.update([["new", "values"]])
+ file.sheet1.update([["new", "values"]]) # unchanged

- file.sheet1.update("B2:C2", [["54", "55"]])
+ file.sheet1.update([["54", "55"]], "B2:C2")
# or
+ file.sheet1.update(range_name="B2:C2", values=[["54", "55"]])

More

See More Migration Guide

Change colors from dictionary to text

v6 uses hexadecimal color representation. Change all colors to hex. You can use the compatibility function gspread.utils.convert_colors_to_hex_value() to convert a dictionary to a hex string.

- tab_color = {"red": 1, "green": 0.5, "blue": 1}
+ tab_color = "#FF7FFF"
file.sheet1.update_tab_color(tab_color)

Switch lastUpdateTime from property to method

- age = spreadsheet.lastUpdateTime
+ age = spreadsheet.get_lastUpdateTime()

Replace method Worksheet.get_records

In v6 you can now only get all sheet records, using Worksheet.get_all_records(). The method Worksheet.get_records() has been removed. You can get some records using your own fetches and combine them with gspread.utils.to_records().

+ from gspread import utils
  all_records = spreadsheet.get_all_records(head=1)
- some_records = spreadsheet.get_all_records(head=1, first_index=6, last_index=9)
- some_records = spreadsheet.get_records(head=1, first_index=6, last_index=9)
+ header = spreadsheet.get("1:1")[0]
+ cells = spreadsheet.get("6:9")
+ some_records = utils.to_records(header, cells)

Silence warnings

In version 5 there are many warnings to mark deprecated feature/functions/methods. They can be silenced by setting the GSPREAD_SILENCE_WARNINGS environment variable to 1

Add more data to gspread.Worksheet.__init__

  gc = gspread.service_account(filename="google_credentials.json")
  spreadsheet = gc.open_by_key("{{key}}")
  properties = spreadsheet.fetch_sheet_metadata()["sheets"][0]["properties"]
- worksheet = gspread.Worksheet(spreadsheet, properties)
+ worksheet = gspread.Worksheet(spreadsheet, properties, spreadsheet.id, gc.http_client)

More Examples

Opening a Spreadsheet

# You can open a spreadsheet by its title as it appears in Google Docs
sh = gc.open('My poor gym results') # <-- Look ma, no keys!

# If you want to be specific, use a key (which can be extracted from
# the spreadsheet's url)
sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')

# Or, if you feel really lazy to extract that key, paste the entire url
sht2 = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl')

Creating a Spreadsheet

sh = gc.create('A new spreadsheet')

# But that new spreadsheet will be visible only to your script's account.
# To be able to access newly created spreadsheet you *must* share it
# with your email. Which brings us to…

Sharing a Spreadsheet

sh.share('[email protected]', perm_type='user', role='writer')

Selecting a Worksheet

# Select worksheet by index. Worksheet indexes start from zero
worksheet = sh.get_worksheet(0)

# By title
worksheet = sh.worksheet("January")

# Most common case: Sheet1
worksheet = sh.sheet1

# Get a list of all worksheets
worksheet_list = sh.worksheets()

Creating a Worksheet

worksheet = sh.add_worksheet(title="A worksheet", rows="100", cols="20")

Deleting a Worksheet

sh.del_worksheet(worksheet)

Getting a Cell Value

# With label
val = worksheet.get('B1').first()

# With coords
val = worksheet.cell(1, 2).value

Getting All Values From a Row or a Column

# Get all values from the first row
values_list = worksheet.row_values(1)

# Get all values from the first column
values_list = worksheet.col_values(1)

Getting All Values From a Worksheet as a List of Lists

from gspread.utils import GridRangeType
list_of_lists = worksheet.get(return_type=GridRangeType.ListOfLists)

Getting a range of values

Receive only the cells with a value in them.

>>> worksheet.get("A1:B4")
[['A1', 'B1'], ['A2']]

Receive a rectangular array around the cells with values in them.

>>> worksheet.get("A1:B4", pad_values=True)
[['A1', 'B1'], ['A2', '']]

Receive an array matching the request size regardless of if values are empty or not.

>>> worksheet.get("A1:B4", maintain_size=True)
[['A1', 'B1'], ['A2', ''], ['', ''], ['', '']]

Finding a Cell

# Find a cell with exact string value
cell = worksheet.find("Dough")

print("Found something at R%sC%s" % (cell.row, cell.col))

# Find a cell matching a regular expression
amount_re = re.compile(r'(Big|Enormous) dough')
cell = worksheet.find(amount_re)

Finding All Matched Cells

# Find all cells with string value
cell_list = worksheet.findall("Rug store")

# Find all cells with regexp
criteria_re = re.compile(r'(Small|Room-tiering) rug')
cell_list = worksheet.findall(criteria_re)

Updating Cells

# Update a single cell
worksheet.update_acell('B1', 'Bingo!')

# Update a range
worksheet.update([[1, 2], [3, 4]], 'A1:B2')

# Update multiple ranges at once
worksheet.batch_update([{
    'range': 'A1:B2',
    'values': [['A1', 'B1'], ['A2', 'B2']],
}, {
    'range': 'J42:K43',
    'values': [[1, 2], [3, 4]],
}])

Get unformatted cell value or formula

from gspread.utils import ValueRenderOption

# Get formatted cell value as displayed in the UI
>>> worksheet.get("A1:B2")
[['$12.00']]

# Get unformatted value from the same cell range
>>> worksheet.get("A1:B2", value_render_option=ValueRenderOption.unformatted)
[[12]]

# Get formula from a cell
>>> worksheet.get("C2:D2", value_render_option=ValueRenderOption.formula)
[['=1/1024']]
### Add data validation to a range

```python
import gspread
from gspread.utils import ValidationConditionType

# Restrict the input to greater than 10 in a single cell
worksheet.add_validation(
  'A1',
  ValidationConditionType.number_greater,
  [10],
  strict=True,
  inputMessage='Value must be greater than 10',
)

# Restrict the input to Yes/No for a specific range with dropdown
worksheet.add_validation(
  'C2:C7',
   ValidationConditionType.one_of_list,
   ['Yes',
   'No',]
   showCustomUi=True
)

Documentation

Documentation: https://gspread.readthedocs.io/

Ask Questions

The best way to get an answer to a question is to ask on Stack Overflow with a gspread tag.

Contributors

List of contributors

How to Contribute

Please make sure to take a moment and read the Code of Conduct.

Report Issues

Please report bugs and suggest features via the GitHub Issues.

Before opening an issue, search the tracker for possible duplicates. If you find a duplicate, please add a comment saying that you encountered the problem as well.

Improve Documentation

Documentation is as important as code. If you know how to make it more consistent, readable and clear, please submit a pull request. The documentation files are in docs folder, use reStructuredText markup and rendered by Sphinx.

Contribute code

Please make sure to read the Contributing Guide before making a pull request.

gspread's People

Contributors

aiguofer avatar alexmalins avatar alifeee avatar andrewbasem1 avatar burnash avatar butvinm avatar candeira avatar cclauss avatar ccppoo avatar cgkoutzigiannis avatar chisvi avatar cstarner avatar dependabot[bot] avatar dgilman avatar fendse avatar flantasticdan avatar idonec avatar jlumbroso avatar laike9m avatar lavigne958 avatar mephinet avatar msuozzo avatar muddi900 avatar neolooong avatar oskarbrzeski avatar p-doyle avatar rafa-guillermo avatar thebestmensch avatar timgates42 avatar yongrenjie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gspread's Issues

Feature Request: Identify cells by color

This is a very useful Python library. I've been using it for the past several months to read and write to Google spreadsheets.

I want to be able to identify cells based on the cell's color. I have a spreadsheet with peach-colored cells, and I want to write a program (using gspread) to write in "0"s into only the peach-colored cells. I know gspread doesn't support color-identification yet. So, this is a feature request. Would this be possible to get color-identification in gspread? Does the original Google spreadsheet API support this?

Python 2.5 support

Hi,

I dont know if its out of scope of this project, but python 2.5 support rather doable if we kill all the python 2.6+ pythoness:)
(python 2.5 is used in Debian 5.0 (Lenny))

Im not really used to git, but here is the patch:
https://gist.github.com/2603120

What needed to be changed:
I.
except HTTPError as ex: -> except HTTPError, ex

The "as" keyword is new in python 2.6

II.
Unpacking a method calling:

  •    return self.update_cell(*(self.get_int_addr(label)), val=val)
    
  •    [one,two] = self.get_int_addr(label)
    
  •    return self.update_cell(one, two, val=val)
    

Dunno why python 2.5 have not accepted it.

III. .format method
String does not have .format method, it was introduced in python 3.0, and backported to python 2.6.
So I wrote a small replacement method. It is quite dumb, but do the job.
(only supports our dictionary case, while the new .format method supports list too)

IV. The next() builtin call is introduced in python 2.6 too.
I wrote/found a little replacement try-catch function.
+try: next
+except NameError:

  • def next (obj): return obj.next()

Best,
Laszlo

Add ability to create a new spreadsheet

Should be possible create a new spreadsheet

gc = gspread.login( 'user', 'password' )

spreadsheet_name = 'My spreadsheet Name'
new_spreadsheet = gc.new( spreadsheet_name )

wks = gc.open( spreadsheet_name ).sheet1

....

Best Regards and congratulations, gspread is very cool!

Search for value

Feature request for searching for cells by value. For example:

col_id, row_id = worksheet.find("Account name")

Return cell's address?

Burnash, you are wonderful for publishing gspread. Thank you.

Is there any way to capture a cell's address? For instance, I'd like to find a value in a spreadsheet and then do something like cell_address=cell.address for R6C1. I would use this value then to capture an entire row.

Thanks again for gspread,

burnash.value = awesome

'UnicodeEncodeError' when sheet name contains non-ascii characters

Hi! Testing out the library, I seem to have discovered that the name of the worksheet trips up things when it contains non-ascii characters.

For example, having a sheet named 'Första' gives the following error in the console:

>>> gc = gspread.login('myuser', 'mypass')
>>> sht = gc.open('My test spreadsheet')
>>> sht.sheet1
    Traceback (most recent call last):
         File "<console>", line 1, in <module>
         UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 13: ordinal not in range(128)

Accessing properties on the worksheet directly, like sht.sheet1.id works as expected, however, so it seems it has to do with the actual representation of the worksheet in Python (probably?).

Script Hangs

Got a situation where sometimes my script hangs.. no timeout no nothing..

Don't know if there is anything that can be done to "help" this situation

This is the backtrace after around 15 mins.

File "./alcontrol.py", line 150, in
sheet.update_cell(curr_row, c, data[ki])
File "/home/geo2lab/geo2pylons/shell/gspread/models.py", line 343, in update_cell
self._cell_addr(row, col))
File "/home/geo2lab/geo2pylons/shell/gspread/client.py", line 224, in get_cells_cell_id_feed
r = self.session.get(url)
File "/home/geo2lab/geo2pylons/shell/gspread/httpsession.py", line 62, in get
return self.request('get', url, *_kwargs)
File "/home/geo2lab/geo2pylons/shell/gspread/httpsession.py", line 57, in request
return request.urlopen(req)
File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 369, in _call_chain
result = func(_args)
File "/usr/lib/python2.7/urllib2.py", line 1193, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1154, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "/usr/lib/python2.7/httplib.py", line 955, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 989, in _send_request
self.endheaders(body)
File "/usr/lib/python2.7/httplib.py", line 951, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 811, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 773, in send
self.connect()
File "/usr/lib/python2.7/httplib.py", line 1158, in connect
self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file)
File "/usr/lib/python2.7/ssl.py", line 344, in wrap_socket
ciphers=ciphers)
File "/usr/lib/python2.7/ssl.py", line 121, in init
self.do_handshake()
File "/usr/lib/python2.7/ssl.py", line 283, in do_handshake
self._sslobj.do_handshake()
KeyboardInterrupt

Set/Modify sheet protection

I ran into some problems when other people modify the Google doc while my script is processing.
Is it possible to set the sheet protection (Tools->Protect Sheet "Who is allowed to modify the sheet") to "Only by me" while via the module and then set it back to its initial status after having finished the editing?
Does your current implementation allow to easily use 'http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#AccessControlLists' ?

If so I could try to add this (it might take some time though as I am new to Python.

Using OAuth2 authentication

Is it possible to use this api with Oauth2 token authentication ?

Like this:

token = gdata.gauth.OAuth2Token( .......)
self.gd_client = gdata.spreadsheets.client.SpreadsheetsClient()
token.authorize(self.gd_client)

Thanks

worksheet.append_row not working.

I can connect to spreadsheet and worksheet ok.
I can add and update values of single cells with both methods: worksheet.update_acell and worksheet.update_cell just fine.
But the append_row method will not work.

Edit.
Just realised that it actually works but it starts appending to row 101.
You have to delete all the blank rows after creating new spreadsheet.

btw. Thanks for the great library!

Add ability to add/remove comments and notes for cells

It would be really nice to be able to work with comments or notes via gspread. To be honest, I have doubts whether this is possible with current Google API, but I never worked with it before so I could be wrong.

If you have any idea, how this possibly could be done, but this feature doesn't fit your plans for the next release, please write it here - I will try to implement it myself. I need it for my own project, though it is not essential, but surely is nice to have.

And thanks for gspread, it is very cool :)

Best Regards,
Iurii

Date Problems

I dont know quite what is going on with the API..

I have a raw spreadsheet, ie NO formatting, repeat NO formatting of cells and am throwing data in via gspread... and in the UK..

As I'm using google from domains,, ie a domain spreasheet and not a personal gmail one.. I have set the "domain" locale to UK english and lang..

These entries when typed manualy into a sheet come out corretly as
"25/12/012" = next xmas

25/12/2012 = the same
25-12-2012 = converts to 25/12/2012
2012-12-25 = converts to 25/12/2012

Now with the API all sorts of stuff happens.. my source data is mysql so format is YYYY-mm-dd
And indeed mad stuff happens, whether transmitted as dd/mm/YYYY or dd-mm-YYYYY
eg sometimes it converts 11/01/2011 into 01/11/2011
This is a BIG issue and lots of bugs somehow..

The only way I can make it work at the momment is to send
"12 December 2012" and this converts to 25/12/2012

My suspicion is that the google xml-API is somehow
converting uk dates to USA
and then "programatically updating" into UK format spredsdheet...
or something like that..

So we need to experiment a bit to get to the root of problem, and embed that in the client lib maybe..
certainly handing dates and date/time objects over without having to do the formatting would be nice..

Is there a way to get the spreasheets locale ?

Writing UTF-8 encoded values

I have problems with writing UTF-8 encoded non-Ascii values to spreadsheets.
Browsing through the code l of update_cell lead me to:

self.client.put_feed(uri, ElementTree.tostring(feed)) and I saw that

xml.etree.ElementTree.tostring(element, encoding="us-ascii", method="xml")
Generates a string representation of an XML element, including all subelements. element is an Element instance. encoding [1] is the output encoding (default is US-ASCII). method is either "xml", "html" or "text" (default is "xml"). Returns an encoded string containing the XML data.

So an option would be to allow encoding='utf-8' for those who need it. Or I got it wrong and the problem is somewhere else.

TypeError: POST data... with urllib

I'm getting this traceback when attempting to use this in Python 3.2.3, and I'm not exactly sure what to do:

>>> gc = gspread.login(email,password)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    gc = gspread.login(email,password)
  File "C:\Python32\lib\site-packages\gspread-0.0.12-py3.2.egg\gspread\client.py", line 273, in login
    client.login()
  File "C:\Python32\lib\site-packages\gspread-0.0.12-py3.2.egg\gspread\client.py", line 82, in login
    r = self.session.post(url, data)
  File "C:\Python32\lib\site-packages\gspread-0.0.12-py3.2.egg\gspread\httpsession.py", line 65, in post
    return self.request('post', url, data=data, **kwargs)
  File "C:\Python32\lib\site-packages\gspread-0.0.12-py3.2.egg\gspread\httpsession.py", line 57, in request
    return request.urlopen(req)
  File "C:\Python32\lib\urllib\request.py", line 138, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python32\lib\urllib\request.py", line 367, in open
    req = meth(req)
  File "C:\Python32\lib\urllib\request.py", line 1065, in do_request_
    raise TypeError("POST data should be bytes"
TypeError: POST data should be bytes or an iterable of bytes. It cannot be str.

Documentation

This is already outta date
http://burnash.github.com/gspread/reference.html#models

So maybe enable the wiki for docs..
or spool out the html docs with the spreadsheet...

I prefer both but we need to have matching local docs used.. hence the static html spooled..

But "you can create then yourself".. but no sphinx installed on windows machine so another problemm... html is small files to penalty is zero for benefit of end user..

The idea anyway...


Then

Can the pages for API be seperate..
so Spreadheet in one page
Cells in another
worksheets in another..

Feature request: Insert row(s) at location

Is it possible to create a method that would insert n rows in a specific location? The end of a spreadsheet is not always the desired place for new data. :)

p.s. Thanks for publishing gspread! It's saved me a ton of time and hassle.

delete_row(idx)

Currently its not possible to remove a row apart from resizing and in this case the row needs to be at the end..

I have a situation where I need to delete a row in the "middle"..

Keep up the good work Anton ;-)))

Pluggable ElementTree

There should be a way to allow usage of lxml since the API is compatible with ElementTree

Quickest update methods

I am using this API in a chunk of software for automated testing and uploading resulting data to a spreadsheet to share.

I am noticing some lag on uploads and I can easily work around it, but I want to make sure I am not doing it wrong or there is a much quicker way. Essentially I am updating a cell at a time. The row can change often so I figured it would be easier to go by row number over cell name like "A1".

workSheet.update_cell(conInfo[0],1,time.strftime("%Y-%m-%d %H:%M:%S", conInfo[1]))
workSheet.update_cell(conInfo[0],2,conInfo[2])
workSheet.update_cell(conInfo[0],3,conInfo[3])
workSheet.update_cell(conInfo[0],4,conInfo[4])

Manually create a cell list

I am wondering if it is, or could be, possible to manually make a cell list and then say were on the spreadsheet to upload it too.

My thinking is that instead of retrieving a cell list, updating values then sending it you could just create the list and send it saving time.

Catch get_worksheet() error

spreadsheet.get_worksheet() throws an error.

Should either
return None (preffered by me)
or throw and exception

for m in range(1, 13):

    sheet = spreadsheet.get_worksheet(m)
    cell = sheet.cell(1,1)

File "./xxl.py", line 64, in
sheet = spreadsheet.get_worksheet(m)
File "gspread/models.py", line 86, in get_worksheet
return self._sheet_list[index]
IndexError: list index out of range

Float value problem(s)

Hi !

First, thanks for this lib, very useful and easy-to-use !

I'm having a problem with some float numbers..
Because I'm European my Google Spreadsheet uses comma as seperating dot for float numbers.

Though, sometimes instead of commas some of the values generated by my python script had a dot, so GDoc couldn't understand it. (First issue)

Because I couldn't easily find the origin of this problem, I decided to transform numbers before writing them to the spreadsheet.
I simply did that :

wks.update_acell("XY", str(value).replace(".",","))

But, with more than 2 digits, it doesn't work, the comma is removed by update_acell (Second issue)
Example :
wks.update_acell("F202", str(2.41).replace(".",",")) => "2,41"
wks.update_acell("F202", str(2.413).replace(".",",")) => "2413"

Thank you !

Best practice for creating relationships

I've got plenty of experience with databases in general, but I've never tried using a spreadsheet as a data source. Assuming I need to model the relationship between artists and albums, how would I do that using google spreadsheet?

I've created worksheets for artists and albums but I'm not clear on how to avoid duplicating data. Do I just set an arbitrary ID on the artists sheet, and use that ID in the album sheet? The amount of data in this will be very small...perhaps only 30 artists total.

Updating tables triggers error

First of all, thanks for writing such a useful library. This is making my day a lot easier, and the possibilities by connecting Google Spreadsheet to scripts look interesting.

I got a problem when I try to update the fields. After finding the spreadsheet, and also after reading values I tried to update values, but I didn't quite get it to work. I tried both

cell_list = worksheet.range("H2:H5")

for cell in cell_list:
cell.value = "Hurray, this works"

worksheet.update_cells(cell_list)

and

worksheet.update_acell("H2", "Hello")

but for both I get en error message saying:

Traceback (most recent call last):
File "check_country_in_gdoc.py", line 23, in
worksheet.update_cells(cell_list)
File "/Library/Python/2.7/site-packages/gspread/models.py", line 441, in update_cells
self.client.post_cells(self, ElementTree.tostring(feed))
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/xml/etree/ElementTree.py", line 1127, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/xml/etree/ElementTree.py", line 821, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/xml/etree/ElementTree.py", line 933, in _serialize_xml
v = _escape_attrib(v, encoding)
File "/Library/Python/2.7/site-packages/gspread/models.py", line 33, in _escape_attrib
text = _elementtree_escape_attrib(text)
TypeError: _escape_attrib() takes exactly 2 arguments (1 given)

Screen Shot 2013-02-01 at 4 15 56 PM

Error: "from .client import Client, login"

I tried to install the gspread library by cloning into my local directory. Then I cd into the cloned gspread directory and type "python setup.py install", according to the user guide:
http://burnash.github.io/gspread/userguide.html I get this error message and I'm not sure if the issue is the gspread library or with my machine (MacBook Air, 10.8.3). Does anyone else get this error, too?

$ python setup.py install
Traceback (most recent call last):
File "setup.py", line 4, in
import gspread line 14 from .client import Client, login
SyntaxError: invalid syntax

EDIT: Making a virtual env solves the problem.

sheet.row_values(1) crashed with ValueError

Here;s the test code, creating a new Worksheet, and then want to check the first row

    tab_label = month_labels[m - 1]
    try:
        sheet = spreadsheet.worksheet(tab_label)

    except gspread.exceptions.WorksheetNotFound:
        sheet = spreadsheet.add_worksheet( tab_label, 1, len(col_defs) )
        print "created"

    print "sheet=", sheet

    first_col = sheet.row_values(1) #<< error 
    print first_col

heet= <Worksheet "Jan" id:od2>
Traceback (most recent call last):
File "./alcontrol.py", line 87, in
first_col = sheet.row_values(1)
File "/home/geo2lab/geo2pylons/shell/gspread/models.py", line 286, in row_values
last_index = max(cells.keys())
ValueError: max() arg is an empty sequence

App Engine?

Has anyone been able to use gspread on App Engine?

I'm using it in an app on the local development environment, works really well. Once I get into production though I'm getting "Application Error: 5" repeatedly.. bummer!

Just seeing if anyone has any insight..

Thanks!

Errors and Exceptions

Firstly, i want to thank you for the work you've done, it's been incredibly easy to integrate my Google Document as the storage for my data logging.

I'm fairly new to Python, and most of my "coding" consists of finding examples online and tailoring them to work with what I'm looking to do.

My code is running on a Raspberry Pi and designed to pull the indoor/outdoor temperature, and log it to a spreadsheet. When I use URLlib to pull that data, I use the try:, except syntax to catch errors and not crash the program.

Previously, I was updating one cell at a time, which took much longer, and would lock up the program every few days. When I went to my spreadsheet, the row of data would be partially updated. I understood that as the communication between the program and Google failing, causing the program to lock up. I read some of the posts and converted my program to update an entire row at one time, with one API call. That sped up the program, and allowed it to run for longer periods of time before locking up.

That all being said, how would I add a error handler to catch when it fails and prevent it from locking up? Would I do that when I do the login call, the spreadsheet open call, or the update_cells call?

Thank you for any help!

Edward

Unable to authenticate. 403 code

Trying to login to test this library out and I'm getting an error. I've made sure to install gspread. I created a single python file, test.py. My code is as simple as it gets:

import gspread

# Login with your Google account
gc = gspread.login('<username>', '<password>')

Yet when I run this via the terminal python test.py I get the following error:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    gc = gspread.login('<username>', '<password>')
  File "/Library/Python/2.7/site-packages/gspread/client.py", line 278, in login
    client.login()
  File "/Library/Python/2.7/site-packages/gspread/client.py", line 99, in login
    raise AuthenticationError("Unable to authenticate. %s code" % ex.code)
gspread.exceptions.AuthenticationError: Unable to authenticate. 403 code

I confirmed that my login credentials were correct by logging out of Google docs, then logging back in, then copying and pasting the u/p into test.py and still nothing. Any suggestions?

Change cell's background color

Is it possible to change a cell's background color?

I made a workaround, I upload the rows with the color as text in the first column, then I wrote/adapted a
serverside (they call google apps script) script to change from text to color, and an another one from color back to text.

Now when I modify a row's color, I always run this little helper script. The problem with this solution,
that google's scripts are awesomely slow, a 400 rows table takes approximately 3 minutes to be finished.
And also it is still manual work. (and I need to remember who modified the table last the user or the program).

If I could somehow modify the background color using gspread, I would immediately switch to it.

On the serverside script, I use these methods (if it is any help):
var range = SpreadsheetApp.getActiveSheet().getDataRange();
range.setBackgroundColor("#ff0000");

I can post the full serverside script, if it helps. I dont mind to share at all.

Best,
Laszlo

numericise(None) raises TypeError, aborting entire sheet load

We are doing:

wksheet.get_all_records()

And for some worksheets containing formulas referencing other sheets, we are getting a TypeError for a NoneType in one of the cells. This can be repro'd directly with:

from gspread import utils
utils.numericise(None)
Traceback (most recent call last):
File "", line 1, in
File "...server/venv/lib/python2.7/site-packages/gspread/utils.py", line 73, in numericise
value = int(value)
TypeError: int() argument must be a string or a number, not 'NoneType'

numericise should check for None and not raise an exception.

newline chars lost during cell update

Hi,

worksheet.update_cells(cell) does not update the cells correctly.
All newline chars in the cell get erased. So if you have a multiline entry in your table's cell, and you retrieve it with gspread and save it back, the multiline cell transformed into a single line.

This is rather annoying bug for me, that is the only one preventing me using gspread daily.

Best,
Laszlo

HTTPError: HTTP Error 409: Conflict When doing multiple cell updates

I have a feeling I am trying to shove too much information too quickly, or incorrectly, to my google spreadsheet. When I try to do some basic stress testing I eventually get the error.

It looks like the error is from a conflict.
image

I am loading an upload queue which when and object is pulled from it I get about 4 points of information from it and upload each cells updates individually. I am thinking google might prefer that I update a range of cells, which I am guessing might reduce overhead. Before I spent too much time guessing and checking I figured I might get some input on how this might be happening and how to handle it.

Case Example

Just thought I'd explain how I'm using as an example - would have sent u message but github says no email address to contact..

All I need is a spreadsheet to display "summary" reports for staff.. available online (downlaod or live)

So the app needs to
Generate a spreadhseet for the year
Create a Summary worksheet == sheet1
Create the Jan-Dec worksheets/tabs

  • if not exits, create and insert header columns (first row)

Get the completed jobs from database
-- find the correct month worksheet
-- find the jobno in the first col
+++ if not exist insert_row
-- if it exists, check if any values changes locally, and update any cells changed

Now I have spend HOURS on trying to do this with openoffice/python and was a waste of time.. too complicated
The gdata API sucks,
Your API is fantastic and simple... love it and thanks.. (have u got a dontate button?)

feature request: fetch specific row or column range

the gdocs api doc talk about a way to fetch a range of columns or rows. I'm using Python so their online example doesnt help me much.
Wondering if adding this functionality is on your roadmap?

I didnt see anything in your worksheet api doc that suggest you already have this feature supported... and I'm not interested in the range() method which needs a defined boundary.
the google docs talks about a min_row/max_row and min_col/max_col attributes of the CellQuery object, but I could never get it working properly.

gdoc docs is here https://developers.google.com/google-apps/spreadsheets/#fetching_specific_rows_or_columns

I supposed I could always call the col_values() method for each column I need to fetch but that seems inefficient to me :)
thanks!

Cell range

This should be helpful, say to extract a cell range:

cells = worksheet.cellrange('B2:B12')

Type Casting problem

I'm having to update a cell with an int as value, gpread reports an error during request..

TypeError: cannot serialize 11796L (type long)

I am not sure what is the best solution, apart from my side typcasting everyhitn to a string.

option 1

  • report an error before the request is made.. ie in update_cell() (if isinstance(v, int) : Throw error

option 2

  • Converts int, floats, decimals to unicode automatically...but that leads to another series of problems maybe..

Traceback (most recent call last):
File "./alcontrol.py", line 151, in
sheet.update_cell(curr_row, c, data[ki])
File "/home/geo2lab/geo2pylons/shell/gspread/models.py", line 348, in update_cell
self.client.put_feed(uri, ElementTree.tostring(feed))
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1121, in tostring
ElementTree(element).write(file, encoding, method=method)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 815, in write
serialize(write, self._root, encoding, qnames, namespaces)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 934, in _serialize_xml
_serialize_xml(write, e, encoding, qnames, None)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 927, in _serialize_xml
v = _escape_attrib(v, encoding)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1087, in _escape_attrib
_raise_serialization_error(text)
File "/usr/lib/python2.7/xml/etree/ElementTree.py", line 1047, in _raise_serialization_error
"cannot serialize %r (type %s)" % (text, type(text).name)
TypeError: cannot serialize 11796L (type long)

SpreadsheetNotFound, WorksheetNotFound

when opening a spreadsheet by title with the gc.open('incorrect title') method, and assuming I'm passing an incorrect title, the Spreadsheet error doesnt output anything (unlike AuthenticationError).
WorksheetNotFound doesnt seem to fire if i'm trying to open a worksheet with a non-existant index. get_worksheet(999)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.