Skip to content

Instantly share code, notes, and snippets.

@simonkeng
Forked from soobrosa/csv_to_google_sheets.py
Last active August 9, 2017 20:03
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 simonkeng/63d22cb3b00be3adbdf5a35acad36d32 to your computer and use it in GitHub Desktop.
Save simonkeng/63d22cb3b00be3adbdf5a35acad36d32 to your computer and use it in GitHub Desktop.
CSV to Google Sheets, command line tool using gspread and oauth2client with Sheets API
# My fork of this script
# I am using an older version of oauth2client
# if you encounter problems with import errors for oauth2
# try doing:
# pip install oauth2client==1.5.2
# Usage:
# python push_to_google_sheets.py filename.csv sheet_name
#
# In case your Google Account protected
# with Two Factor Authorization,
# you have to create an application-specific password
# and use your email to login as usual.
# https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en_GB
#
# Dependency:
# https://github.com/burnash/gspread
import json
import sys
import gspread
from oauth2client.client import SignedJwtAssertionCredentials
import os
def main(argv):
json_key = json.load(open('creds.json')) # json credentials you downloaded earlier
scope = [
'https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive'
]
# credentials = ['--EMAIL--', '--TOKEN--']
credentials = SignedJwtAssertionCredentials(json_key['client_email'],
json_key['private_key'].encode(),
scope)
if len(argv) < 2:
sys.stderr.write("Usage: %s filename.csv sheet_name" % (argv[0],))
return 1
if not os.path.exists(argv[1]):
sys.stderr.write("ERROR: File %r was not found!" % (argv[1],))
return 1
gc = gspread.authorize(credentials)
wks = gc.open(argv[2]).sheet1
fi = open(argv[1])
row = 1
column = 1
for li in fi:
items = li.strip().split(',')
for item in items:
wks.update_cell(row, column, item)
column += 1
row += 1
column = 1
worksheet.update_cells(cell_list)
fi.close()
if __name__ == '__main__':
sys.exit(main(sys.argv))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment