python + googledrive:上传xlsx,转换为googlesheet,获取可共享链接

2024-03-01

我想要的程序的流程是:

  1. 上传 xlsx 电子表格到驱动器(它是使用 pandas 创建的to_excel)
  2. 将其转换为 Google 表格格式
  3. 指定任何知道该链接的人都可以对其进行编辑
  4. 获取链接并与将输入信息的人共享
  5. 下载完成的表格

我目前正在使用PyDrive,它解决了步骤1和5,但还有一些未解决的问题。

如何转换为谷歌表格格式?我尝试将 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})

对于“INSERT”和“COPY”方法都有一个可选的查询参数“convert”;

convert=true,

是否将此文件转换为相应的 Google Docs 格式。 (默认值:假)

这里有一个 python 示例:

Google 文档 - 复制 https://developers.google.com/drive/v2/reference/files/copy

您需要使用 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

我还没有尝试过这个,所以你需要测试一下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python + googledrive:上传xlsx,转换为googlesheet,获取可共享链接 的相关文章

随机推荐