如何用Python的gspread按条件筛选Google Sheets指定单元格数据?
使用gspread筛选Google Sheet指定数据
核心实现代码及步骤:
完成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读取数据并筛选
用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
相关产品推荐
相关产品推荐

