繁体   English   中英

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

[英]How to Convert XLSX to Sheets in Google Drive API v3

当我将 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. )它应该可以正常工作!

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

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

可以参考谷歌官方文档,有一个参数convert convert=true,可以将文件转换为对应的谷歌文档格式(默认:false)。

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

找到这个 Stack Overflow 票,检查社区提供的解决方案: python + google drive:上传 xlsx,转换为谷歌表,获取可共享链接

def uploadExcel(excelFileName):
   file_metadata = {'name': excelFileName, 'parents': [folderId], 'mimeType': 'application/vnd.google-apps.spreadsheet'}
   media = MediaFileUpload(excelFileName, mimetype='application/vnd.ms-excel', resumable=True)
   file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()

逻辑是:我们想要从excel格式创建电子表格

所以我们完全按照这个逻辑编码(C# 的例子):

Google.Apis.Drive.v3.Data.File fileMetadata = new Google.Apis.Drive.v3.Data.File();
            fileMetadata.Name = System.IO.Path.GetFileName(file_being_uploaded);
            fileMetadata.Description = "File created via Google Drive API C#";
            fileMetadata.MimeType = "application/vnd.google-apps.spreadsheet";
            fileMetadata.Parents = new List<string> { _parent };    // if you want to organize in some folder       

            // File content.
            byte[] byteArray = System.IO.File.ReadAllBytes(file_being_uploaded);
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
            try
            {
                FilesResource.CreateMediaUpload request = _service.Item1.Files.Create(fileMetadata, stream, GetMimeType(file_being_uploaded));
(...)

    // gets us the Excel Mime
    private static string GetMimeType(string fileName)
    {
        string mimeType = "application/unknown";
        string ext = System.IO.Path.GetExtension(fileName).ToLower();
        Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
        if (regKey != null && regKey.GetValue("Content Type") != null)
            mimeType = regKey.GetValue("Content Type").ToString();
        return mimeType;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM