Search code examples
pythongoogle-sheetsgspread

AttributeError: 'Spreadsheet' object has no attribute 'range'


Hi stackoverflow community, I am new to python. I want to edit a google spreadsheet using gspread. The following is the code I am using:

import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

json_key = json.load(open('My Project-f3f034c4a23f.json'))
scope = ['https://spreadsheets.google.com/feeds']

credentials = ServiceAccountCredentials.from_json_keyfile_name('My Project-f3f034c4a23f.json', scope)
gc = gspread.authorize(credentials)

worksheet = gc.open('Roposo')

worksheet.update_acell('B1', 'Gspread!')

I am getting the error:

Traceback (most recent call last): File "C:\Users\user\Desktop\Python\spreadsheet.py", line 16, in cell_list = worksheet.range('A1:C7') AttributeError: 'Spreadsheet' object has no attribute 'range'

Please tell a suitable solution.


Solution

  • Your variable worksheet is the whole spreadsheet document not a worksheet. You should do something like

    ss = gc.open('Roposo')
    ws = ss.worksheet('myWorksheet') 
    ws.update_acell('B1', 'Gspread !') 
    

    if a worksheet named 'myWorksheet' already exists. Otherwise create a new worksheet with:

    ss = gc.open('Roposo')
    ws = ss.add_worksheet('title', 100, 20) #title, row, col
    ws.update_acell('B1', 'Gspread !')
    

    The API documentation describes the two objects Spreadsheet and Worksheet more in detail.