python gspread library only writes to worksheet labeled 'sheet1'

泄露秘密 提交于 2019-12-24 15:59:03

问题


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?


回答1:


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)




回答2:


client = gspread.authorize(creds)

sheet = client.open('name').worksheet('name/title')


来源:https://stackoverflow.com/questions/33570749/python-gspread-library-only-writes-to-worksheet-labeled-sheet1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!