python gspread library only writes to worksheet labeled 'sheet1'
Asked Answered
L

2

9

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?

Leventhal answered 6/11, 2015 at 15:59 Comment(0)
D
32

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)

Diphenylamine answered 9/11, 2015 at 7:19 Comment(2)
thanks for getting back to me, i've had some trouble with gsheets lately. my biggest problem is in this post where i'm having connection time out issues, would you know an answer to this one? #33597161Leventhal
@user3768071sorry I don't have a good suggestion for that issue. I will get back to you at the time I can figure out oneDiphenylamine
P
5
client = gspread.authorize(creds)

sheet = client.open('name').worksheet('name/title')
Papism answered 5/3, 2019 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.