gpt4 book ai didi

python - 如何在 Google Drive API v3 中将 XLSX 转换为表格

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:00 24 4
gpt4 key购买 nike

当我将 xlsx 文件连同我的代码上传到 Google Drive 时,我想将它们自动转换为 Google 电子表格。但是,虽然 csv 文件的转换成功,但我得到:

<HttpError 400 when requesting https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&alt=json returned "Bad Request">

尝试上传 xlsx 时。

这是我的代码:

def upload_service(filepath, name="", description="", fileID="", parentID=""):
""" Uses a Resource (service) object to upload a file to drive. """

if service == "": authenticate_service()

if name == "":
name = str(os.path.basename(filepath).split(os.extsep)[0]) # Get from filepath

extension = str(os.path.basename(filepath).split(os.extsep)[1]).lower()

if extension == "csv": # CSV
mime_type = "text/csv"
elif extension in ["xls", "xlsx"]: # EXCEL
mime_type = "application/ms-excel"
else:
return

media_body = MediaFileUpload(filepath, mimetype=mime_type, resumable=True)

if parentID == "":
meta = dict(name=name, mimeType="application/vnd.google-apps.spreadsheet", description=description)
else:
meta = dict(name=name, mimeType="application/vnd.google-apps.spreadsheet", description=description, parents=[parentID])

if fileID == "": # CREATE
upload = service.files().create(
body=meta,
media_body=media_body).execute()
else: # REPLACE
upload = service.files().update(
body=meta,
media_body=media_body,
fileId=fileID).execute()

print ("\nFINISHED UPLOADING")

我如何在 v3 中执行此操作?在 v2 中非常清楚如何做到这一点,但在更新的 API 中却没有。

最佳答案

在 APIv3 中,您需要为发生的转换指定一个非常具体的 MIME 类型。

https://developers.google.com/drive/v3/web/manage-uploads#importing_to_google_docs_types_wzxhzdk8wzxhzdk9 ,您会注意到语句“支持的转换在关于资源的 importFormats 数组中动态可用”。使用任一方法获取 importFormats 列表

GET https://www.googleapis.com/drive/v3/about?fields=importFormats&key={YOUR_API_KEY}

或转到 https://developers.google.com/drive/v3/reference/about/get#try-it并输入 importFormats

您会在响应中注意到:

"application/vnd.ms-excel": [
"application/vnd.google-apps.spreadsheet"
]

在您的代码中,使用:

elif extension in ["xls", "xlsx"]:      # EXCEL
mime_type = "application/vnd.ms-excel"

(注意额外的 vnd.)它应该可以正常工作!

关于python - 如何在 Google Drive API v3 中将 XLSX 转换为表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36948862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com