Created
September 30, 2016 23:42
-
-
Save yosemsweet/00ed89269e7be9e8fdee33b1215deacd to your computer and use it in GitHub Desktop.
Connecting and writing to a spreadsheet
This file contains 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
from __future__ import print_function | |
import httplib2 | |
import os | |
from apiclient import discovery | |
import oauth2client | |
from oauth2client import client | |
from oauth2client import tools | |
from oauth2client.service_account import ServiceAccountCredentials | |
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' | |
CREDENTIALS = 'service-account.json' | |
CLIENT_SECRET_FILE = 'client_secret.json' | |
APPLICATION_NAME = 'Google Sheets API Python Quickstart' | |
def get_credentials(): | |
"""Gets Service Account credentials. | |
""" | |
from oauth2client.service_account import ServiceAccountCredentials | |
credentials = ServiceAccountCredentials.from_json_keyfile_name( | |
CREDENTIALS, scopes=SCOPES) | |
return credentials | |
def main(): | |
"""Shows basic usage of the Sheets API. | |
Creates a Sheets API service object and prints the names and majors of | |
students in a sample spreadsheet: | |
https://docs.google.com/spreadsheets/d/1fgOEqugOhbsV_Ntq53xqY40i3otkA-4Qq-uzQaT1q3M/edit | |
""" | |
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) | |
spreadsheetId = '1fgOEqugOhbsV_Ntq53xqY40i3otkA-4Qq-uzQaT1q3M' | |
rangeName = 'current-metric!A2:B2' | |
values = [ | |
[ | |
"2016-09-30 23:42:14-07:00", 129452 | |
] | |
] | |
body = { | |
'values': values | |
} | |
result = service.spreadsheets().values().update( | |
spreadsheetId=spreadsheetId, range=rangeName, | |
valueInputOption="RAW", body=body).execute() | |
print(result) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment