Search code examples
pythonexceltraceback

"ImportError: cannot import name 'styles' from 'gspread2'" when trying to create a .py program that will read my google sheet


I read about gspread2 and tried to give it a go.

I created the API credentials, and downloaded the JSON token.

I tried the following code to test if I could read from my target cell as a test:

from gspread2.models import Workbook

URL = 'https://docs.google.com/spreadsheets/d/[REDACTED]'
CREDENTIALS = 'C:/Users/USERNAME/Documents/REDACTED.json'

workbook = Workbook(URL, CREDENTIALS)

worksheet = workbook['Sheet 1']

selected_cell = worksheet.cell('B2')
print(selected_cell)

It throws me the traceback:

ImportError: cannot import name 'styles' from 'gspread2' 
(C:\Users\USERNAME\AppData\Local\Programs\Python\Python37\lib\site-packages\gspread2\__init__.py)
  • I have tried against python 3.6, 3.7 and 3.8 both from the microsoft store and from the python website. The same error.

  • I have also tried solutions from similar errors in other libraries and none of them worked.

I also checked the __init.py__ file for instances of styles and it doesn't seem to have any.

I'm fairly new with coding, and I'm at a loss on what to do next.

Any ideas will be really appreciated.


Solution

  • It looks like a bug in gspread2's packaging which fails to bundle and install the gspread2.styles package. The source is on github gspread2. This line in setup.py needs changing from

    packages=['gspread2'],
    

    to

    packages=['gspread2', 'gspread2.styles'],
    

    You may want to contact the authors. As for a temporary fix for now, you could download the package from github

    git clone https://github.com/futuereprojects/gspread2
    

    make the fix and then, in the gspread directory run, python3 setup.py install. Or find out where the packages is currently installed and copy the styles subdirectory into it.