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

如何通过Python访问Google Drive“已与我共享”文件夹中的Excel文件

可行解决方案汇总

方法1:使用Google Drive API 直接读取共享文件

凭借文件查看权限,可通过Google Drive API直接获取最新文件内容,步骤如下:

  1. 前往Google Cloud控制台创建项目,启用Drive API并生成服务账号密钥(JSON格式)。
  2. 请客户将服务账号的邮箱添加至共享文件的查看权限列表。
  3. 借助google-api-python-client和pandas实现读取:
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
from google.oauth2 import service_account
import io
import pandas as pd

# 加载服务账号密钥
SERVICE_ACCOUNT_FILE = 'your-service-account-key.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE)
drive_service = build('drive', 'v3', credentials=credentials)

# 从共享链接提取文件ID(格式:https://drive.google.com/file/d/[FILE_ID]/view)
file_id = 'your-shared-file-id'

# 请求导出为Excel格式(适配原文件为Excel的场景)
request = drive_service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()

# 读取至DataFrame
fh.seek(0)
df = pd.read_excel(fh)

此方法支持每日动态更新,每次运行代码都会拉取最新文件内容。

方法2:转换共享链接为直接下载链接(无需API)

若共享链接具备“查看权限”,可将其转换为直接下载格式:

  1. 从共享链接提取FILE_ID(规则同方法1)。
  2. 构造下载链接:https://drive.google.com/uc?export=download&id=FILE_ID
  3. 用pandas直接读取:
import pandas as pd

file_id = 'your-shared-file-id'
url = f'https://drive.google.com/uc?export=download&id={file_id}'
df = pd.read_excel(url)

该方法同样会每次拉取最新内容,若文件较大可能需处理Google的临时验证,但查看权限下通常可直接下载。

方法3:处理.gsheet快捷方式文件(解决你之前的问题)

快捷方式生成的.gsheet本质是Google Sheets的指向链接,可通过gspread库读取:

  1. 复用方法1的服务账号,将其邮箱添加至原Google Sheets的查看权限。
  2. 安装依赖库:
pip install gspread pandas gspread-dataframe
  1. 读取代码:
import gspread
from gspread_dataframe import get_as_dataframe
import pandas as pd

# 初始化客户端
gc = gspread.service_account(filename='your-service-account-key.json')

# 从快捷方式链接提取.gsheet文件ID
sheet_id = 'your-shortcut-sheet-id'
# 打开目标工作表
worksheet = gc.open_by_key(sheet_id).sheet1
# 转换为DataFrame
df = get_as_dataframe(worksheet)

此方法支持动态更新,每次运行都会读取最新的工作表内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 16:16:04