Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Export a Google Spreadsheet using python.
#!/usr/bin/python
import re, urllib, urllib2
class Spreadsheet(object):
def __init__(self, key):
super(Spreadsheet, self).__init__()
self.key = key
class Client(object):
def __init__(self, email, password):
super(Client, self).__init__()
self.email = email
self.password = password
def _get_auth_token(self, email, password, source, service):
url = "https://www.google.com/accounts/ClientLogin"
params = {
"Email": email, "Passwd": password,
"service": service,
"accountType": "HOSTED_OR_GOOGLE",
"source": source
}
req = urllib2.Request(url, urllib.urlencode(params))
return re.findall(r"Auth=(.*)", urllib2.urlopen(req).read())[0]
def get_auth_token(self):
source = type(self).__name__
return self._get_auth_token(self.email, self.password, source, service="wise")
def download(self, spreadsheet, gid=0, format="csv"):
url_format = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=%s&exportFormat=%s&gid=%i"
headers = {
"Authorization": "GoogleLogin auth=" + self.get_auth_token(),
"GData-Version": "3.0"
}
req = urllib2.Request(url_format % (spreadsheet.key, format, gid), headers=headers)
return urllib2.urlopen(req)
if __name__ == "__main__":
import getpass
import csv
email = "" # (your email here)
password = getpass.getpass()
spreadsheet_id = "" # (spreadsheet id here)
# Create client and spreadsheet objects
gs = Client(email, password)
ss = Spreadsheet(spreadsheet_id)
# Request a file-like object containing the spreadsheet's contents
csv_file = gs.download(ss)
# Parse as CSV and print the rows
for row in csv.reader(csv_file):
print ", ".join(row)
@mikejones222
Copy link

mikejones222 commented Feb 10, 2015

How do you get this to correctly write into a csv. I'm getting all of my columns in Column A with commas separating them.

@a-b
Copy link

a-b commented Jul 28, 2015

docs.google.com/feeds/download/spreadsheets/Export?key<FILE_ID>&exportFormat=csv&gid=0
http://stackoverflow.com/a/12507856/167362

@shyamskcetlib
Copy link

shyamskcetlib commented Feb 13, 2020

hi urllib is not currently available so please give the same code for urllib3 as many function unsupporting

@petrus-v
Copy link

petrus-v commented Jul 23, 2021

@shyamskcetlib google do not support this authentification processus any more you could use or get inspiration from google-sheets-to-csv python package

@4lparslan
Copy link

4lparslan commented Feb 10, 2022

I have authorization to view and download the spreadsheet manually (It is public). So i do not want to log in. How can i just download it?

@petrus-v
Copy link

petrus-v commented Feb 10, 2022

@4lparslan as explain here you can use wget to test direct download with your sheet id then adapt with you programming language and favorite http library !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment