googledriveapiv3下载Google电子表格作为Ex

2024-09-25 00:32:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图下载一个googledrive电子表格作为Excel文件。据我所知,googledriveapi只需为export_media请求指定一个不同的mime类型,就可以使这个过程变得非常简单。在

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

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

完整的脚本是here。要运行,请按照说明在googledriveapi文档中创建应用程序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%,并且从不停止。在


Tags: 脚本id类型applicationexportmediavndsheet
1条回答
网友
1楼 · 发布于 2024-09-25 00:32:25

结果是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'])

但是,在调试器中,我可以看到它们不在响应中。因此,它不知道什么时候完成。在

^{pr2}$

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

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

相关问题 更多 >