使用gspread和pandas从Google Sheet按行色筛选生成DataFrame的方法
Google Sheet按行颜色筛选生成DataFrame实现方案
该需求完全可实现,核心逻辑是通过Google Sheets API读取行的背景填充色属性,和默认无填充的属性值做对比筛选后,即可生成符合要求的DataFrame,同时支持筛选带颜色行和无颜色行。
依赖工具
- Python环境下依赖
gspread(调用Google Sheets API读写数据及格式)、gspread-dataframe(实现gspread和pandas数据格式转换)、pandas(DataFrame结构处理) - 需要提前开通Google Cloud的Sheets API并拿到授权凭证,确保凭证有目标表格的读取权限
核心实现步骤
1. 初始化连接并读取基础数据
import gspread import pandas as pd # 凭证初始化,使用自己的Google Cloud服务账号凭证文件 gc = gspread.service_account(filename="service_account.json") # 打开对应表格,替换为自己的表格ID/名称 sh = gc.open_by_key("你的表格ID") worksheet = sh.get_worksheet(0) # 读取全表数值,拆分表头和数据行 all_values = worksheet.get_all_values() headers = all_values[0] data_rows = all_values[1:]
2. 获取全表单元格格式属性
# 读取所有单元格的格式配置 all_formats = worksheet.get_all_formatting()
3. 按颜色筛选行并生成DataFrame
默认无填充的行,单元格背景色的RGB值为(1,1,1)对应白色#FFFFFF,如果你的表格默认背景有特殊设置,可以先打印1行无标注行的格式属性确认基准判断值。
colored_rows = [] uncolored_rows = [] # 遍历数据行,跳过表头,格式列表的索引和数据行索引差1 for row_idx, row_data in enumerate(data_rows): # 取行首单元格的背景色作为整行颜色标识(整行统一填充场景适用) cell_bg = all_formats[row_idx+1][0].get("backgroundColor", {}) # 判断是否为自定义填充色 is_colored = not ( cell_bg.get("red", 1) == 1 and cell_bg.get("green", 1) == 1 and cell_bg.get("blue", 1) == 1 ) if is_colored: colored_rows.append(row_data) else: uncolored_rows.append(row_data) # 生成对应DataFrame colored_df = pd.DataFrame(colored_rows, columns=headers) uncolored_df = pd.DataFrame(uncolored_rows, columns=headers)
注意事项
- 如果表格不是整行统一填充颜色,可调整判断逻辑,遍历该行所有单元格的背景色,只要有一个单元格符合颜色要求就判定为符合条件
- 如果需要筛选特定颜色的行,只需要把判断条件替换为对应颜色的RGB值匹配即可
内容的提问来源于stack exchange,提问作者russianmax
相关产品推荐
相关产品推荐

