python + google drive: upload xlsx, convert to google sheet, get sharable link

djsensei picture djsensei · Feb 27, 2015 · Viewed 7.1k times · Source

The flow of my desired program is:

  1. Upload an xlsx spreadsheet to drive (it was created using pandas to_excel)
  2. Convert it to Google Sheets format
  3. Specify that it is editable by anyone with the link
  4. Get the link and share it with someone who will enter information
  5. Download the completed sheet

I am currently using PyDrive, which solves steps 1 and 5, but there are a few unsolved problems.

How can I convert to google sheets format? I tried to just specify the mimeType as 'application/vnd.google-apps.spreadsheet' when I created the file to upload with PyDrive, but that gave me an error.

How can I set the file to be editable by anyone with the link? Once that is set, I can get the sharing link easily enough with PyDrive.

UPDATE: conversion from xlsx to google sheets is easy with a convert=True flag. See below. I am still seeking a way to set the sharing settings of my new file to "anyone with the link can edit".

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

test_file = drive.CreateFile({'title': 'testfile.xlsx'})
test_file.SetContentFile('testfile.xlsx')
test_file.Upload({'convert': True})

Answer

Alan Wells picture Alan Wells · Feb 27, 2015

There is an Optional query parameter of "convert", for both the "INSERT" and "COPY" method;

convert=true,

Whether to convert this file to the corresponding Google Docs format. (Default: false)

There is a python example here:

Google Documentation - Copy

You need to use the Python client library for the code to work.

from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

def insert_file(service, title, description, parent_id, mime_type, filename):
  """Insert new file.

  Args:
    service: Drive API service instance.
    title: Title of the file to insert, including the extension.
    description: Description of the file to insert.
    parent_id: Parent folder's ID.
    mime_type: MIME type of the file to insert.
    filename: Filename of the file to insert.
  Returns:
    Inserted file metadata if successful, None otherwise.
  """
  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
    'title': title,
    'description': description,
    'mimeType': mime_type
  }
  # Set the parent folder.
  if parent_id:
    body['parents'] = [{'id': parent_id}]

  try:
    file = service.files().insert(
        body=body,
        convert=true,
        media_body=media_body).execute()

    # Uncomment the following line to print the File ID
    # print 'File ID: %s' % file['id']

    return file
  except errors.HttpError, error:
    print 'An error occured: %s' % error
    return None

I haven't tried this, so you'll need to test it.