Exporting a Google Docs spreadsheet with Python

This is a small Python module to demonstrate how to export a Googel spreadsheet using gdata-python-client.

To run the module from your Python shell try:


>>> from gdocexport import export_spreadsheet
>>> export_spreadsheet('you@gmail.com', 'password', 'Sheet Title', 'test.csv')

Source

""" 
 Export Google Docs Spreadsheets
 This code is placed in the public domain
 Author: Hans Christian von Stockhausen, 2011-10-10

 Depends on http://code.google.com/p/gdata-python-client/
"""

import gdata.docs.data
import gdata.docs.client
import gdata.spreadsheet.service


def export_spreadsheet(username, password, title, file_path):
    """
    This function: first creates a Google Docs client to find the spreadsheet
    by title. Once it has found the spreadsheet it gets a Google spreadsheets
    auth token, which is required to export the spreadsheet.
    If there are more than one spreadsheet matching the title only the first 
    is exported.

    @username - your Google docs email address
    @password - your Google password
    @title - the title of the spreadsheet
    @file_path - file to export to including file format extension, e.g. .csv

    """

    client = _create_client(username, password)
    feed = client.GetDocList(uri='/feeds/default/private/full?title=%s'
        '&title-exact=true&max-results=1' % title)
    if len(feed.entry) > 0:
        entry = feed.entry[0]
        client.auth_token = _get_spreadsheets_auth_token(username, password)
        client.Export(entry, file_path)

def _create_client(username, password):
    client = gdata.docs.client.DocsClient(source='hcvst-spreadsheetexport-v1')
    client.ssl = True
    client.ClientLogin(username, password, client.source)
    return client

def _get_spreadsheets_auth_token(username, password):
    client = gdata.spreadsheet.service.SpreadsheetsService()
    client.ClientLogin(username, password)
    auth_token = gdata.gauth.ClientLoginToken(client.GetClientLoginToken())
    return auth_token
Advertisements
This entry was posted in python and tagged , , , , . Bookmark the permalink.

One Response to Exporting a Google Docs spreadsheet with Python

  1. Liam says:

    I found gdata-python-client’s api too complicated. The alternative module gspread (https://github.com/burnash/gspread) is a better bet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s