[Tutorial][gspread] How to get a list of all spreadsheets.

Set up a gspread client:

def upload_to_google_sheets(master_board):
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name("filepath", scope)
    gc = gspread.authorize(credentials)

You’ll need the client method openall(). It returns a list of spreadsheet objects. Then use a for-loop to add the title of the spreadsheet to a list.

    titles_list = []
    for spreadsheet in gc.openall():
        titles_list.append(spreadsheet.title)

Then use the “not in” feature of python to check for the title of the spreadsheet you’re interested in accessing or creating.

If it doesn’t exist, create it and share it (it’s very important to share it otherwise you won’t be able to do much with it). I set email1 to the email in the json file you create when setting up gspread.

If it doesn’t exist and you just created it, or if it already existed, then you open it.

    if master_board not in titles_list:
        sh = gc.create(master_board)
        sh.share("email1", perm_type='user', role='writer')
        sh.share("email2", perm_type='user', role='writer')
    wks = gc.open(master_board).sheet1

And that’s how searched all available spreadsheets. Once I had that it was pretty easy to either create one if the one I wanted didn’t exist, or to open it if it did.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s