Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python gspread library only writes to worksheet labeled 'sheet1'

My sheet is named 'doc_name', and it has two worksheets, 'sheet1' and 'sheet2'. but, i can only write data to the worksheet labeled 'sheet1'?

is this a limitation or am i doing something wrong?

this works,

wks = gc.open("doc_name").sheet1

but this fails,

wks = gc.open("doc_name").sheet2

giving this error,

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

i also notice that this fails,

wks = gc.open("doc_name").Sheet1

...where i use a capital 'S'.. and it will only write if i specify lowercase .sheet1

how do i write to a worksheet without having to code... wks = gc.open("doc_name").sheet1?

like image 686
user3768071 Avatar asked Nov 06 '15 15:11

user3768071


2 Answers

This is because gspread only implemented sheet1 to let you retrieve the first sheet in your spreadsheet as a shortcut.

From the source code you can see the implementation of sheet1 is using get_worksheet(0)

@property
def sheet1(self):
    """Shortcut property for getting the first worksheet."""
    return self.get_worksheet(0)

So if you want to retrieve other sheets, you need to use other methods like:

1.specify index as a integer indicating the position of the sheet to open starting from 0:

wks = gc.open("doc_name").get_worksheet(index)

or

2.specify title of the sheet to open as a string:

wks = gc.open("doc_name").worksheet(title)

That is to say, in you case, to get sheet2 you can probably use

wks = gc.open("doc_name").get_worksheet(1)

like image 130
Jerry Zhang Avatar answered Oct 18 '22 00:10

Jerry Zhang


client = gspread.authorize(creds)

sheet = client.open('name').worksheet('name/title')
like image 3
akamtoliya Avatar answered Oct 18 '22 01:10

akamtoliya