Skip to content

Instantly share code, notes, and snippets.

@matabares
Last active October 11, 2019 02:54
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 matabares/d6ece4d09a2d293ed4a82551ed0e8e51 to your computer and use it in GitHub Desktop.
Save matabares/d6ece4d09a2d293ed4a82551ed0e8e51 to your computer and use it in GitHub Desktop.
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import pandas as pd
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SAMPLE_SPREADSHEET_ID = 'HERE YOUR SPREADSHEET ID'
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(
'HERE_YOUR_CREDENTIAL_FILE.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
#SAMPLE RANGE: Cities Base!A:J
worksheet = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,range='HERE_A_RANGE').execute()
table = worksheet.get('values', [])
##Convert table data into a dataframe
df = pd.DataFrame(table[1:], columns=table[0])
##Convert number strings to floats and ints
df = df.apply(pd.to_numeric, errors='ignore')
#Show first rows
df.head()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment