1

我想将我的代码上传到Google云端硬盘时自动将xlsx文件转换为Google电子表格。然而,虽然转换成功为csv文件,我得到:如何在Google Drive API v3中将XLSX转换为表格

<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中。

回答

4

在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.),它应该工作得很好!

+0

这对我有效! – Elliptica

0

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

遇到此错误时,建议的操作是使用exponential backoff。它是网络应用程序的标准错误处理策略,其中客户端在日益增长的时间内定期重试失败的请求。

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

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

发现这个堆栈溢出票,检查由社区提供的解决方案:python + google drive: upload xlsx, convert to google sheet, get sharable link

+0

您引用的参数是Google v2选项,而此问题涉及v3。 Google v3未提供该参数,并且[docs](https://developers.google.com/drive/v3/web/migration#notable_changes)建议的方法无效。 – Elliptica

相关问题