Skip to content

Instantly share code, notes, and snippets.

@AlJohri
Last active November 9, 2018 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlJohri/8cad01f786c269b73f6d21e13fc9d0ca to your computer and use it in GitHub Desktop.
Save AlJohri/8cad01f786c269b73f6d21e13fc9d0ca to your computer and use it in GitHub Desktop.
# pip install google-api-python-client
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
def get_sheet(sheet_id, range_str):
result = service.spreadsheets().values().get(spreadsheetId=sheet_id,
range=range_str).execute()
rows = result.get('values', [])
fieldnames = rows[0]
return [{fieldnames[i]:col for i, col in enumerate(row)} for row in rows[1:]]
def update_sheet(sheet_id, range_str, rows, fieldnames=None):
fieldnames = list(rows[0].keys()) if not fieldnames else fieldnames
values = [fieldnames] + [[row.get(col, '') for col in fieldnames] for row in rows]
body = {'values': values}
result = service.spreadsheets().values().update(spreadsheetId=sheet_id,
range=range_str,
valueInputOption="USER_ENTERED",
body=body).execute()
return result
if __name__ == "__main__":
FILE_ID="xyz"
rows = get_sheet(FILE_ID, 'output!A:C')
rows[0]['col1'] = 'changed222222222!'
result = update_sheet(FILE_ID, 'output!A:C', rows)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment