Morpheus.47
Morpheus.47

Reputation: 131

How do I get all records from all sheets (tabs) in a google spreadsheet using one API call?

I wanted to retrieve all the records from a google spreadsheet in one api call (instead of looping through all the sheets and retrieving them one-by-one). Currently I'm doing this

creds = ServiceAccountCredentials.from_json_keyfile_name('path-to-key', 'key.json'), self.scope)
client = gspread.authorize(creds)
spread = client.open("My SpreadSheet")

data_for_sheet_0 = spread.get_worksheet(0).get_all_records()
data_for_sheet_1 = spread.get_worksheet(1).get_all_records()
.
.
.

As you can see, this is not efficient. Is there any way to get all of the sheet data (or the entire spreadsheet as an Iterable of Iterables)? Thanks.

Upvotes: 2

Views: 4804

Answers (1)

Kingson
Kingson

Reputation: 119

Try this. By using spreadsheet.worksheets() Checkout this gspread documentation: https://gspread.readthedocs.io/en/latest/user-guide.html#selecting-a-worksheet

creds = ServiceAccountCredentials.from_json_keyfile_name('path-to-key', 'key.json'), self.scope)
client = gspread.authorize(creds)
spread = client.open("My SpreadSheet")

#Getting a list of worksheets inside a spreadsheet.
sheets = spreadsheet.worksheets()

for sheet in sheets:
    record = sheet.get_all_records()

    # Do whatever you want
    print(record)

Upvotes: 3

Related Questions