python + google drive: upload xlsx, convert to goo

2019-04-23 18:04发布

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})

2条回答
相关推荐>>
2楼-- · 2019-04-23 18:41

In order to set the file to be editable for anyone with the link , you have to insert a new permission with the following information:

from apiclient import errors
# ...

def share_with_anyone(service, file_id):
  """Shares the file with anyone with the link

  Args:
    service: Drive API service instance.
    file_id: ID of the file to insert permission for.

  Returns:
    The inserted permission if successful, None otherwise.
  """
  new_permission = {
      'type': "anyone",
      'role': "writer",
      'withLink': True
  }
  try:
    return service.permissions().insert(
        fileId=file_id, body=new_permission).execute()
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

then to get the link you go to : file["alternateLink"]

查看更多
We Are One
3楼-- · 2019-04-23 18:50

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.

查看更多
登录 后发表回答