Python + Google Drive:上传XLSX,转换为Google表格,获取共享链接。

11

我期望程序的流程如下:

  1. 上传一个使用 pandas 的 to_excel 函数创建的 xlsx 电子表格到谷歌网盘
  2. 将其转换为谷歌表格格式
  3. 指定任何持有链接的人都可以进行编辑
  4. 获取链接并与需要输入信息的人分享
  5. 下载已完成的表格

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

如何转换为谷歌表格格式?我尝试在使用 PyDrive 上传文件时将 mimeType 指定为 'application/vnd.google-apps.spreadsheet',但是出现了错误。

如何设置文件让持有链接的任何人都可以进行编辑?一旦设置好,我便可轻松地通过 PyDrive 获取共享链接。

更新:使用 convert=True 标志很容易实现从 xlsx 到谷歌表格的转换。请参见下文。我仍在寻找一种方法来将我的新文件共享设置为“任何持有链接的人都可以进行编辑”。

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

我不确定这是否是最佳答案,但如果其他方法都失败了,您可以调用一个执行所需操作的Apps Script应用程序。您需要运行一个HTTP请求。访问-权限 - Alan Wells
谢谢您的提问。您有没有找到使用pydrive添加权限的方法? - tol4trob
2个回答

4

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

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

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


谢谢!在PyDrive中成功添加了convert=True标志作为Upload()方法的输入参数。请参见我上面问题中的更新代码。 - djsensei

3
为了使任何拥有该链接的人都能编辑文件,您需要插入以下信息的新权限:
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

然后要获取链接,你需要访问:file["alternateLink"]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接