2

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.

Aman Baweja
  • 35
  • 1
  • 1
  • 4

1 Answers1

4

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.

Jacques Gaudin
  • 15,779
  • 10
  • 54
  • 75
  • Hi Jacques, your answer works when I create a new worksheet, but the following error comes up when I do use this code: `ss = gc.open('Roposo') ws = ss.get_worksheet('Aworksheet') ws.update_acell('B1', 'Gspread !')` Error: File "C:\Users\user\Desktop\Python\spreadsheet.py", line 15, in ws = ss.get_worksheet('Aworksheet') File "build\bdist.win32\egg\gspread\models.py", line 154, in get_worksheet return self._sheet_list[index] Type Error: list indices must be integers, not str – Aman Baweja May 18 '16 at 09:14
  • Oh sorry, the `get_worsheet` function takes an intger index as only parameter. Use `worksheet` instead to look up by title. Answer amended accordingly. – Jacques Gaudin May 18 '16 at 09:18
  • Thanks for the help Jacques – Aman Baweja May 18 '16 at 09:37