Connect Google Spreadsheet using Python code example

Connect Google Spreadsheet using Python code example

Google Spreadsheet

Refers to Google Spreadsheet solution which a cloud based application similar to Microsoft Excel. To connect with Google Spreadsheet we need to install gspread library which can be done using below statement:

pip install gspread

Once gspread is installed follow the steps to enable Google API access:

  • Create a Project on Google
  • Enable the Project
  • Create Service Account Key by clicking on Option
  • Select the Project and Owner In Role
  • Click on Json and download the file

Note: This json file includes your specific credentials to access this project and it’s the only copy. Keep this file safe and keep it secure. For the purpose of this project, the simplest thing to do is to also store this JSON file in the same directory as your code.

Open the JSON file using any Text Editor and copy the information followed by “client_email:”.

Important: Go to the spreadsheet you wish to access with your Python code and share it with the email you copied from “client_email:”. This is required as you need to give your API Credentials access to your spreadsheet.

Code example

import gspread
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('JSON file name', 'scope')
gc = gspread.authorize(credentials)
sheet = gc.open_by_url('Google Spreadsheet URL goes here')
worksheet = sheet.get_worksheet( worksheet index. The index starts at 0)

Finally, you got access to your desired sheet. Now your can play around with various functions exposed by gspread library using python.

Next Read/Write PDF using Python

Leave a Reply

Your email address will not be published. Required fields are marked *