Search code examples
pythongoogle-apps-scriptgoogle-sheets

Trigger python code from Google spreadsheets?


In excel you can create user defined functions with python using pyxll. I have been moving to Google spreadsheets and using their Google app script, but the libraries are so much bigger and better in python, I wish there was a way to build user defined functions using python from Google spreadsheets. There are ways to interact python with Google sheets like gspread. Is there a way to run python on Google app engine then get sheet to trigger that code? What other ways is there to trigger python code from Google spreadsheets?


Solution

  • One way is to have some code that reads the spreadsheet all the time, then runs some other code when a condition is met.

    Without GAE, you could use the following code:

    #http://code.google.com/p/gdata-python-client/downloads/list
    import gdata.spreadsheet.service as s
    
    spreadsheet_key = 'spreadsheetkey'# https://docs.google.com/spreadsheet/ccc?key=<spreadsheet key>&usp=sharing#gid=0
    
    worksheet_key = 'od6' #first tab
    gd_client = s.SpreadsheetsService(spreadsheet_key, worksheet_key)
    gd_client.email = '[email protected]'
    gd_client.password = 'password'
    gd_client.ProgrammaticLogin()
    list_feed = gd_client.GetListFeed(spreadsheet_key, worksheet_key)
    for entry in list_feed.entry:
        #read cell values and then do something if the condition is met
    

    If you wanted to have the spreadsheet run code in a GAE app, then you could publish the spreadsheet and construct the URL of the spreadsheet (JSON) like this: https://spreadsheets.google.com/feeds/list/(spreadsheetkey)/od6/public/values?alt=json This address can be accessed via the app, the cell values can be read, and some code can be triggered.

    The approach is the same with both ideas: some code monitors the spreadsheet and when some condition is met, some other code is triggered. I'm not sure how you could run the code (in a GAE app, say) when the condition is met purely from the Google Spreadsheet.