Reputation: 2399
The Python API for Google sheets has a get
method to get values from a spreadsheet, but it requires a range
argument. I.e., your code must be something like this,
sheets_service = service.spreadsheets().values()
data = sheets_service.get(spreadsheetId = _GS_ID, range = _SHEET_NAME).execute()
and you cannot omit the range
argument, nor will a value of ''
work, or a value of 'Sheet1'
or similar (unless there is a sheet named Sheet1
).
What if I do not know the sheet name ahead of time? Can I reference the first or left-most sheet somehow? Failing that, is there a way to get a list of all the sheets? I have been looking at the API and have not found anything for that purpose, but this seems like such a basic need that I feel I'm missing something obvious.
Upvotes: 3
Views: 5206
Reputation: 201418
You can retrieve the values and metadata of Spreadsheet using spreadsheets.get
of Sheets API. By using the parameter of fields
, you can retrieve various information of the Spreadsheet.
This sample retrieves the index, sheet ID and sheet name in Spreadsheet. In this case, index: 0
means the first sheet.
service.spreadsheets().get(spreadsheetId=_GS_ID, fields='sheets(properties(index,sheetId,title))').execute()
This sample retrieves the sheet name, the number of last row and last column of data range using sheet index. When 0 is used for the sheet index, it means the first sheet.
res = service.spreadsheets().get(spreadsheetId=_GS_ID, fields='sheets(data/rowData/values/userEnteredValue,properties(index,sheetId,title))').execute()
sheetIndex = 0
sheetName = res['sheets'][sheetIndex]['properties']['title']
lastRow = len(res['sheets'][sheetIndex]['data'][0]['rowData'])
lastColumn = max([len(e['values']) for e in res['sheets'][sheetIndex]['data'][0]['rowData'] if e])
Upvotes: 3