python gspread library only writes to worksheet labeled 'sheet1'

user3768071 picture user3768071 · Nov 6, 2015 · Viewed 7.7k times · Source

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?

Answer

Jerry Zhang picture Jerry Zhang · Nov 9, 2015

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)