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

我将自己的代码上传到Google云端硬盘时,我想将xlsx文件自动转换为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中,您需要指定一个非常特定的 MIMEtypes来进行转换。

https://developers.google.com/drive/v3/web/manage-uploads#importing_to_google_docs_types_wzxhzdk8wzxhzdk9&#x4E2D; ,您会注意到“受支持的转化在关于资源的importFormats数组中可dynamic使用”。 使用任何一个获取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并inputimportFormats

你会注意到在回应中:

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

在你的代码中,使用:

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

(注意额外的vnd. ),它应该工作得很好!

根据官方Google文档 ,您收到400: Bad Request ,表示未提供必填字段或参数,提供的值无效或提供的字段组合无效。 尝试添加将在目录graphics中创build循环的父项时,可能会引发此错误。

遇到此错误时,build议的操作是使用exponential backoff 。 对于networking应用程序来说,这是一种标准的error handling策略,在这种策略中,客户机在不断增加的时间内周期性地重试失败的请求

您可以使用官方的Google 文档供您参考,有一个参数convert convert=true,将文件转换为相应的Google Docs格式(默认:false)。

您还需要使用Python client library ,您可以使用该库来支持上载文件。

find这个堆栈溢出票,检查社区提供的解决scheme: python +谷歌驱动器:上传xlsx,转换为谷歌表,获得可共享链接