RemakingEden
RemakingEden

Reputation: 312

How to call a specific sheet within a spreadsheet via the Google Sheets API v4 in Python

I'm pretty new to this stuff and I've really hit a brick wall on an early project of mine.

I've done my best to look everywhere including - Search engines, StackOverflow, the API documentation and I really cannot find the answer anywhere. So I hope its appropriate to ask.

I am trying to view a range from a specific sheet (tab at the bottom) of a Google sheet. I know this sheet has a sheetId that can be found in the url. I can get this, however, I can find absolutely no way to request a specific sheet with this number. I have found ways to use this number to copy and duplicate sheets and I have even found a way to print all the available sheetId's on a spreadsheet.

def suggestion():

SAMPLE_SPREADSHEET_ID = 'mySpreadsheetID'
SAMPLE_RANGE_NAME = 'A1:D12'

"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('creds.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                            range=SAMPLE_RANGE_NAME,).execute()
values = result.get('values', [])

if not values:
    print('No data found.')
else:
    for row in values:
        # Print columns A and E, which correspond to indices 0 and 4.
        print(row)

I believe the answer is probably in here https://developers.google.com/resources/api-libraries/documentation/sheets/v4/python/latest/sheets_v4.spreadsheets.values.html but I can't seem to find it.

Right now the program is opening the default sheet (tab at the bottom) when I would like it to open one of the specific sheets and look for data there.

Thanks for any help in advance. It's appreciated massively!

Upvotes: 6

Views: 8491

Answers (1)

mr.freeze
mr.freeze

Reputation: 14062

Google sheets uses A1 notation to specify a range. This can include the specific tab that you're trying to access values from.

You can specify a tab in your range value by adding the name of the sheet before the range. For example, if you wanted something from Sheet2:

SAMPLE_RANGE = 'Sheet2!A2:E10'

If you rename your sheet tab then you would need to update your range to match it since it is reference by name.

Upvotes: 10

Related Questions