Test a cell on a Google Sheet and write to that row

175 views Asked by At

I've got a Google Sheet with students names (columns A and B) and some value in the column next to it (column C). I'd like to test each value in turn and write to that row's (column D) if the test resolves to True.

My code so far:

from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

# Don't know what this is for
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API'

# just copied code from Google's Dev guide
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

# PROBLEM IS IN THIS METHOD
def main():
    # Hope Google doesn't change all this API stuff and make us redo:
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)
    # Fake URI of our sheet
    spreadsheetId = '5lksdfusdlfkjkj886kJUNKssdff'

    # retrieve data works
    rangeName = 'Sheet1!A2:D70'
    result = service.spreadsheets().values().get(
        spreadsheetId=spreadsheetId, range=rangeName).execute()
    values = result.get('values', [])

    if not values:
        print('No data found.')
    else:
        for row in values:
            print('Checking on: %s %s' % (row[0], row[1]))
            # PROBLEM... can't seem 
            if row[2] == "Some arbitrary condition":
                # Even trying to hardcode a range doesn't work 
                # I'd like to reference the coordinates of this row 
                result = service.spreadsheets().values().update(
                    spreadsheetId=spreadsheetId, range='Sheet1!D64',
                    body="can you see me?").execute()
                print(result)


if __name__ == '__main__':
    main()
0

There are 0 answers