Google Drive API v3 下载 google 电子表格作为 Excel

Google Drive API v3 download google spreadsheet as Excel

我尝试将 Google Drive spreadsheet 下载为 Excel 文件。据我所知,Google Drive API 应该通过为 export_media 请求指定不同的 mime 类型来使这变得非常简单。

根据教程脚本,我可以成功 下载 spreadsheet 作为 CVS 和 Open Office sheet。太棒了!

然而,如果 mime 类型设置为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - 正如 MS Excel 所指定的那样,下载程序会继续从流中读取,而不会停止,也不会增加状态进度。

完整的脚本是here. To run, follow the instructions to create an app in the Google Drive API docs 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% 并且永不停止。

事实证明,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())