This piece of code was part of a larger project. I wanted to share what I learned to help
others navigate how to access a Google Sheets file. In addition, I will discuss how to upload
an Excel file to a Google Sheets file
Google Developer Console Setup
- Go to Google Developer Console
- Click ‘ENABLE APIS AND SERVICES’
- Search ‘google sheets’ and select ‘Google Sheets API’
- Enable the API
- Create a new project and name your project
- Click on OAuth consent screen and select ‘External’
- At the next screen name the Application and then hit save
- Click on Credentials and then click ‘CREATE CREDENTIALS’
- Select OAuth Client ID
- Select other and hit create. Hit ok at the next screen that pops up
- You are now setup with google and should download the json file under OAuth 2.0
Client IDs. This is your client secret file, which in the code below is named ‘client_secret.json’
Python Code: Downloading Google Sheets
File
from __future__ import print_function
import os
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/drive.readonly'
store = file.Storage('###') #Enter the storage location
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('###', SCOPES) ###This is your client secret
creds = tools.run_flow(flow, store)
DRIVE = discovery.build('drive', 'v3', http=creds.authorize(Http()))
FILENAME = 'Enter File Name'
SRC_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
DST_MIMETYPE = 'text/csv'
files = DRIVE.files().list(
q='name="%s" and mimeType="%s"' % (FILENAME, SRC_MIMETYPE),
orderBy='modifiedTime desc,name').execute().get('files', [])
if files:
fn = '### Name of prior file.csv' #Does prior version of file exists?
print('Exporting "%s" as "%s"... ' % (files[0]['name'], fn), end='')
data = DRIVE.files().export(fileId=files[0]['id'], mimeType=DST_MIMETYPE).exec
if data:
with open(fn, 'wb') as f:
f.write(data)
print('DONE')
else:
print('ERROR (could not download file)')
else:
print('!!! ERROR: File not found')
Python Code: Uploading File To Google
Sheets
###Updates EXISTING Google Sheets file
import pygsheets
import pandas as pd
from datetime import date
#authorization
gc = pygsheets.authorize(service_file='JSON CREDENTIALS FILE PATH') #JSON CREDENTIALS
path = '#ENTER FILE PATH'
dt = str(date.today())
#create dataframe
df = pd.read_csv('#ENTER NAME OF FILE')
#open the google spreadsheet (where '#ENTER NAME OF FILE' is the name of my sheet)
sh = gc.open('#ENTER NAME OF FILE')
#selectmro the first sheet
wks = sh[0]
#update the first sheet with df, starting at cell B2.
wks.clear(start='A1', end=None, fields="*")
wks.set_dataframe(df,(1,1),copy_index=False, copy_head=True, fit=True)