python + google drive: загрузить xlsx, конвертировать в Google лист, получить общую ссылку

поток моей желаемой программы:

  1. загрузите таблицу xlsx на диск (она была создана с помощью pandas to_excel)
  2. преобразовать его в формат Google Таблиц
  3. указать, что это для кого есть ссылка
  4. получить ссылку и поделиться ею с кем-то, кто будет вводить информацию
  5. скачать готовый лист

в настоящее время я использую PyDrive, который решает шаги 1 и 5, но есть несколько нерешенных проблем.

как я могу преобразовать в формат Google Таблиц? Я попытался просто указать тип mimeType как 'application/vnd.google-apps.spreadsheet' когда я создал файл для загрузки с PyDrive, но это дало мне ошибку.

как я могу установить файл для редактирования, у кого есть ссылка? Как только это будет установлено, я могу получить ссылку обмена достаточно легко с PyDrive.

обновление: преобразование из xlsx в Google листы легко с convert=True флаг. Увидеть ниже. Я все еще ищу способ установить настройки общего доступа моего нового файла к "любой, у кого есть ссылка, может редактировать".

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 ответов


существует необязательный параметр запроса "convert", как для метода" INSERT", так и для метода" COPY";

convert=true,

нужно ли конвертировать этот файл в формат Google Документов. (По умолчанию: false)

здесь есть пример python:

Документация Google-Копировать

для работы кода необходимо использовать клиентскую библиотеку Python.

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

Я не пробовал это, поэтому вам нужно проверить его.


для того чтобы установить файл для редактирования для тех, кто со ссылкой , Вы должны вставить новое разрешение следующую информацию:

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

затем, чтобы получить ссылку, вы переходите к: файл ["alternateLink"]