You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PyDrive读取Google Drive中xlsx、csv、xls等多种格式的文件

实现PyDrive读取Google Drive多格式表格文件的方案

完全可以实现同时支持读取多种格式文件的需求,核心思路是先获取目标文件的类型属性,再根据类型匹配对应的下载、读取逻辑,即可覆盖Google原生表格、xlsx、xls、csv等常见表格类文件。


1. 前置依赖准备

提前安装所需的依赖库:

  • pydrive:用于Google Drive的认证、文件元信息读取
  • pandas:用于表格数据解析
  • requests:用于文件内容下载
  • 可选:如果需要读取xls格式文件,需安装兼容版本的xlrd:pip install xlrd==1.2.0

2. 完整实现代码

步骤1:初始化认证并获取文件元信息

先通过文件ID拉取文件的MIME类型、文件名,作为后续判断格式的依据:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import requests
import pandas as pd
from io import BytesIO

# 初始化Google Drive认证
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)

# 替换为你要读取的文件ID
target_file_id = "######"
# 拉取文件元信息,包含类型、文件名
file = drive.CreateFile({'id': target_file_id})
file.FetchMetadata(fields='mimeType, title')
file_mime_type = file['mimeType']
file_name = file['title']

步骤2:按文件类型走分支处理逻辑

根据不同的文件类型,调用对应的下载、解析方法:

df = None
# 处理Google原生表格类型
if file_mime_type == 'application/vnd.google-apps.spreadsheet':
    # 原生表格需要先导出为xlsx格式再读取
    export_url = f"https://www.googleapis.com/drive/v3/files/{target_file_id}/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    headers = {"Authorization": f"Bearer {gauth.attr['credentials'].access_token}"}
    res = requests.get(export_url, headers=headers)
    res.raise_for_status()
    df = pd.read_excel(BytesIO(res.content), sheet_name="Summary")
# 处理xlsx、xls格式的普通文件
elif file_mime_type in ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "application/vnd.ms-excel"]:
    download_url = f"https://www.googleapis.com/drive/v3/files/{target_file_id}?alt=media"
    headers = {"Authorization": f"Bearer {gauth.attr['credentials'].access_token}"}
    res = requests.get(download_url, headers=headers)
    res.raise_for_status()
    df = pd.read_excel(BytesIO(res.content), sheet_name="Summary")
# 处理csv格式文件
elif file_mime_type == "text/csv":
    download_url = f"https://www.googleapis.com/drive/v3/files/{target_file_id}?alt=media"
    headers = {"Authorization": f"Bearer {gauth.attr['credentials'].access_token}"}
    res = requests.get(download_url, headers=headers)
    res.raise_for_status()
    # 可根据实际文件编码调整encoding参数,比如gbk、utf-8-sig
    df = pd.read_csv(BytesIO(res.content), encoding='utf-8')
else:
    raise ValueError(f"不支持的文件类型:{file_mime_type},当前仅支持Google表格、xlsx、xls、csv格式")

# 输出读取结果
print(df)

3. 扩展说明

如果需要支持更多格式,只需要在判断分支中新增对应MIME类型的处理逻辑即可;如果需要读取表格内多个sheet,调整pd.read_excel的sheet_name参数即可。

内容的提问来源于stack exchange,提问作者Jore Dawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 22:27:03