5

I am new to python. I was just trying to create a google worksheet using gspread. I read about using google api's from here. I downloaded credentials from Google Developers Console which is a file in json format. Then I used this code

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds']
credentials =     ServiceAccountCredentials.from_json_keyfile_name('spreadsheet1995.json', scope)
gc = gspread.authorize(credentials)
worksheet = gc.add_worksheet(title="A worksheet", rows="100", cols="20")

But it throws an error 'Client' object has no attribute 'add_worksheet' although I read documentation which included this attribute. Here is the link which I followed. Please help me sort out this problem.

Burnash
  • 3,181
  • 2
  • 31
  • 35
Vivek Puri
  • 161
  • 1
  • 1
  • 13

1 Answers1

13

First, you need to know to the difference between a spreadsheet and a worksheet. A spreadsheet is a container of worksheets. Like a book with many pages.

If you go to Google Sheets and hit the big "+" button you will start a new a new spreadsheet. This spreadsheet will at first contain a single worksheet named "Sheet1". You may add more worksheets to your spreadsheet.

Now back to gspread and your code sample.

To create a worksheet you need a spreadsheet. This is what you're missing in your code.

Skipping the authentication part, you code should look like this:

gc = gspread.authorize(credentials)
spreadsheet = gc.open("The name of your spreadsheet")
worksheet = spreadsheet.add_worksheet(title="A worksheet", rows="100", cols="20")

Now with worksheet you may read cell values, edit them, etc.

gspread API Reference

Ctrl S
  • 1,053
  • 12
  • 31
Burnash
  • 3,181
  • 2
  • 31
  • 35
  • Use: spreadsheet.add_worksheet(title="A worksheet", rows="100", cols="20") Instead of: gc.add_worksheet(title="A worksheet", rows="100", cols="20") – kayveesin May 31 '18 at 04:27
  • How do you use the `import_csv` function for a worksheet? How do you add content from scratch in the worksheet? – Suraj Mar 21 '21 at 08:01