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

如何使用Python访问Google Sheets版本历史?可更换gspread外的其他库

访问Google Sheets版本历史的Python方案

gspread库本身没有提供访问Google Sheets版本历史的功能,要实现这个需求,推荐使用google-api-python-client——这是Google官方的Python客户端库,可以完整调用Google Sheets API的所有接口,包括版本历史相关操作。

实现步骤

  1. 安装依赖库
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
  1. 配置认证
  • 在Google Cloud Platform控制台创建项目,启用「Google Sheets API」
  • 生成服务账号密钥(JSON格式),并将该服务账号邮箱共享给目标Google Sheets文档,赋予相应权限
  1. 示例代码(获取版本历史)
from google.oauth2 import service_account
from googleapiclient.discovery import build

# 加载服务账号密钥
SERVICE_ACCOUNT_FILE = '你的服务账号密钥文件路径.json'
# 权限范围:只读版本历史用readonly,需要恢复版本则换成https://www.googleapis.com/auth/spreadsheets
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

# 生成认证凭证
creds = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# 构建Sheets API客户端
service = build('sheets', 'v4', credentials=creds)

# 替换为你的目标表格ID
SPREADSHEET_ID = '你的Google Sheets文档ID'

# 请求版本历史数据
response = service.spreadsheets().get(
    spreadsheetId=SPREADSHEET_ID,
    fields='revisionHistory'
).execute()

# 遍历输出版本信息
revision_history = response.get('revisionHistory', [])
for idx, revision in enumerate(revision_history, 1):
    print(f"版本 {idx}")
    print(f"版本ID: {revision['revisionId']}")
    print(f"修改时间: {revision['modifiedTime']}")
    print(f"修改者: {revision.get('lastEditor', {}).get('displayName', '未记录')}")
    print("-" * 30)

扩展操作

  • 调用service.spreadsheets().revisions().get(spreadsheetId=SPREADSHEET_ID, revisionId=REVISION_ID)可获取单个版本的详细内容
  • 调用service.spreadsheets().revisions().restore(spreadsheetId=SPREADSHEET_ID, revisionId=REVISION_ID)可将文档恢复到指定版本(需对应权限)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 23:57:48