Last active
November 9, 2018 05:48
-
-
Save AlJohri/8cad01f786c269b73f6d21e13fc9d0ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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