使用Python将xlsx文档添加到Google云端硬盘共享文件夹 [英] Add xlsx documents to Google Drive shared folder using Python

查看:61
本文介绍了使用Python将xlsx文档添加到Google云端硬盘共享文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用Python将CSV添加到共享的Google驱动器文件夹中,但是我对脚本中要更改的内容感到困惑,以允许使用Excel文档.这是我的CSV代码.

I'm able to add CSVs to a shared google drive folder using Python, but I'm confused as what to change in my script to allow for excel documents. Here is my code for CSV.

def publish_to_drive(folder_id, path_to_file, filename):
    SCOPES = ['https://www.googleapis.com/auth/drive']
    SERVICE_ACCOUNT_FILE = 'keys.json'
    credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    service = discovery.build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': filename,
        'parents': [folder_id],
        'mimeType': 'text/csv'
    }
    media_body = MediaFileUpload(path_to_file, mimetype='text/csv', 
                                 resumable=True)
    resp = service.files().create(body=file_metadata, media_body=media_body,supportsAllDrives=True).execute()

我意识到需要更改模仿类型,但是我不确定需要将其更改为什么.我尝试了各种方法,但未能找到合适的方法.

I realize that the mimetypes need to be changed, but I'm not sure what they need to be changed to. I've tried various ones but have not been able to get the right ones.

使用正确的mimetypes尝试打开excel文件时,我得到以下信息:

Upon using the right mimetypes I get the following when attempting to open the excel file:

推荐答案

如果在 text/csv 文件类型上使用函数没有问题,那么我相信您只需要更新您的将 mimetype text/csv 转换为 application/vnd.openxmlformats-officedocument.spreadsheetml.sheet .

If there isn't an issue on using function on text/csv file types, then I believe you only need to update your mimetype from text/csv into application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

我在下面添加了一些资源/链接,其中列出了其他哑剧类型,如果您也需要对它们进行处理的话.

I've added some resources/links below that lists other mime types if you need your function to work on them too.

要实际支持多种mime类型,您需要为每种文件类型动态标识 mimetype .您可以通过以下任一方式来做到这一点:

To actually support multiple mime types, you need to dynamically identify the mimetype for each file type. You can do it by either:

  • 简单的字符串操作(如果您看到一个模式),或者在要支持的每个 mimetype 上都有一个条件语句(都不推荐)
  • 出于普遍性考虑,例如.
  • Simple string manipulation (if you see a pattern) or have a conditional statement on each mimetype you want to support (both not recommended)
  • Or for universality, like this.

这篇关于使用Python将xlsx文档添加到Google云端硬盘共享文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆