【问题标题】:Google Drive API v3 download google spreadsheet as ExcelGoogle Drive API v3 将 Google 电子表格下载为 Excel
【发布时间】:2017-10-16 03:54:22
【问题描述】:

我尝试将 Google 云端硬盘电子表格下载为 Excel 文件。据我所知,Google Drive API 应该通过为 export_media 请求指定不同的 mime 类型来简化此操作。

根据教程脚本,我可以成功将电子表格下载为 CVS 并打开 Office 工作表。太好了!

但是,将 mime 类型设置为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - 按照 MS Excel 的指定,下载程序会继续从流中读取,而不会停止,也不会增加状态进度。

完整的脚本是here。要运行,请按照 Google Drive API 文档here中的说明创建应用程序@

有问题的代码在这里:

    file_id = 'my spreadsheet id'

    request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')

    fh = FileIO('data.xls', 'wb')
    downloader = MediaIoBaseDownload(fh, request)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download %d%%." % int(status.progress() * 100))

它会继续打印Download 0% 并且永不停止。

【问题讨论】:

  • 在不同机器上进行测试时,这种行为是否相同?
  • 嗨@AL。我不知道,说实话。我手头只有一个。我可以尝试在容器中运行它。如果你愿意 - 也许你可以在你的机器上运行它?干杯

标签: python google-drive-api google-api-python-client


【解决方案1】:

事实证明,MediaBaseIODownload 依赖于 'content-rangeorcontent-length' 的存在来知道何时停止。

  if 'content-range' in resp:
    content_range = resp['content-range']
    length = content_range.rsplit('/', 1)[1]
    self._total_size = int(length)
  elif 'content-length' in resp:
    self._total_size = int(resp['content-length'])

但是,在我可以看到的调试器中,它们不存在于响应中。因此,它不能不知道何时完成。

  if self._progress == self._total_size:
    self._done = True

解决方案是不运行部分下载,而是完全下载:

request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
with open('data.xlsx', 'wb') as f:
    f.write(request.execute())  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2011-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多