Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a worksheet using gspread

Tags:

python

gspread

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.

like image 909
Vivek Puri Avatar asked Jan 07 '23 04:01

Vivek Puri


1 Answers

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

like image 65
Burnash Avatar answered Jan 19 '23 05:01

Burnash