Skip to content

Instantly share code, notes, and snippets.

@KentaKudo
Created February 3, 2019 08:24
Show Gist options
  • Save KentaKudo/0acdee2876b693d110a1713e122a5353 to your computer and use it in GitHub Desktop.
Save KentaKudo/0acdee2876b693d110a1713e122a5353 to your computer and use it in GitHub Desktop.
A sample code to access Google Sheet in Python
# See: https://developers.google.com/sheets/api/quickstart/python
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] # read/write access
SHEET_ID = '<sheet_id>'
RANGE_NAME = 'original!A1:A1'
def main():
creds = auth()
values = get_values(creds)
if not values:
print('No data found.')
else:
for row in values:
print('%s' % row[0])
def auth():
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def get_values(creds):
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SHEET_ID, range=RANGE_NAME).execute()
return result.get('values', [])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment