Using Python With Google Sheets

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

  1. Go to Google Developer Console
  2. Click ‘ENABLE APIS AND SERVICES’
  3. Search ‘google sheets’ and select ‘Google Sheets API’
  4. Enable the API
  5. Create a new project and name your project
  6. Click on OAuth consent screen and select ‘External’
  7. At the next screen name the Application and then hit save
  8. Click on Credentials and then click ‘CREATE CREDENTIALS’
  9. Select OAuth Client ID
  10. Select other and hit create. Hit ok at the next screen that pops up
  11. 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)

Sharing

Related Articles

  • All Post
  • Articles
  • Blog Post
  • General Business Automation
  • Portfolio
  • Stock Market & Finance