正在导出 Google Sheet 以打开 XML 文档并使用 Python 写入磁盘

Exporting Google Sheet to Open XML Document and writing to disk with Python

我正在使用 GSuite 的 Sheets 进行一些传播sheets,我们用它来填充我们服务的数据库。我正在编写一个小 Python 脚本,它将通过将文件写入本地磁盘来备份我们的文件。

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

我要导出到的mimeType是一个打开的office文档。 Google 关于如何执行此操作的示例如下:https://developers.google.com/drive/api/v3/manage-downloads#python

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

我的方法中的请求对象在调试器中看起来不错,我没有遇到任何异常,程序运行到最后。下载器报告它已完成作业并且大小为 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())

我真正想做的就是获取我的 sheet 并将其写入我的磁盘。任何提示将不胜感激。

干杯,

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

参考: