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

如何用Python的gspread按条件筛选Google Sheets指定单元格数据?

使用gspread筛选Google Sheet指定数据

核心实现代码及步骤:

  1. 完成gspread授权与表格连接
    先通过服务账号或OAuth完成授权,打开目标工作表:

    import gspread
    from google.oauth2.service_account import Credentials
    
    # 配置权限范围,替换为你的服务账号密钥文件路径
    SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
    creds = Credentials.from_service_account_file("service-account-key.json", scopes=SCOPES)
    client = gspread.authorize(creds)
    
    # 打开目标表格,替换为你的表格名称或ID;sheet1为默认第一个工作表,可按需修改
    sheet = client.open("你的表格名称").sheet1
    
  2. 读取数据并筛选
    用get_all_records()将表格数据转为字典列表,方便按表头筛选:

    # 获取所有行数据(包含表头)
    all_data = sheet.get_all_records()
    
    # 筛选出"Fav Book"为"book2"的条目,提取ID和Fav Color
    filtered_items = [
        {"ID": row["ID"], "Fav Color": row["Fav Color"]}
        for row in all_data
        if row["Fav Book"] == "book2"
    ]
    
    # 打印结果
    for item in filtered_items:
        print(f"ID: {item['ID']}, 喜爱颜色: {item['Fav Color']}")
    

补充说明:

  • 如果你的工作表不是第一个,可改用client.open("表格名").worksheet("工作表名")指定
  • 若表格数据量极大,get_all_records()可能效率不高,可改用get_values()读取指定范围再处理,但小数据量下前者更简便

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:42:48