将Google Sheet导出为Open XML文档,并使用Python将其写入磁盘



我正在使用GSuite的Sheets来处理一些电子表格,我们使用这些表格来填充服务的数据库。我正在写一个小Python脚本,它将通过将文件写入本地磁盘来备份我们的文件。

GSuite Sheet对象有一个id,为了导出Google Sheet,至少根据文档,必须使用export_media(fileId, mimeType)

我要导出到的mimeType是一个开放式办公室文档。谷歌关于如何做到这一点的例子如下:https://developers.google.com/drive/api/v3/manage-downloads#python

我的问题是我的文件完全是空的。您会注意到下面代码中的一些print语句,其中输出了一个空字节字符串。

我的方法中的请求对象在调试器中看起来很好,我没有得到任何异常,程序运行到最后。下载器报告它完成了作业,并且大小为21033。我想是以字节为单位的。

这是我用来导出文件并将其写入磁盘的循环和方法。

service = build("drive", "v3", credentials=delegated_credentials, cache_discovery=False)
files = service.files().list(**request_data).execute().get("files", [])
open_type = 'application/x-vnd.oasis.opendocument.spreadsheet'

for f in files:
export_file_to_open_office(f, service, open_type)

def export_file_to_open_office(file, drive_service, mime_type):
request = drive_service.files().export_media(fileId=file["id"], mimeType=mime_type).get()
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
print(fh.read())  # this outputs b''

while done is False:
status, done = downloader.next_chunk()
print(fh.read())  # this outputs b''
print("Download %d%%." % int(status.progress() * 100))

with open("my_file.xls", 'wb') as fil:
fil.write(fh.read())

我真正想做的就是拿到我的单子,把它写在我的磁盘上。任何提示都将不胜感激。

干杯,

C

在您的脚本中,这个修改怎么样?

发件人:

with open("my_file.xls", 'wb') as fil:
fil.write(fh.read())

收件人:

with open("my_file.xls", 'wb') as fil:
fh.seek(0)  # <--- Added
fil.write(fh.read())

参考:

  • 请参见((

最新更新