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

如何使用gspread和pandas获取单元格的字体及字体颜色格式

获取Google表格单元格字体及字体颜色的方法

gspread的acell()方法默认仅返回单元格值,要获取格式信息,需要调用Google Sheets API的高级字段,通过get()方法指定参数实现:

  1. 确保使用最新版gspread,旧版本可能不支持格式字段获取
  2. 使用get()方法替代acell(),指定需要提取的格式字段

代码示例

client = gspread.service_account_from_dict(creds)
hrfile = client.open('HR Data')
hrsheet = hrfile.get_worksheet(0)

# 获取B3单元格的文本格式信息
cell_format = hrsheet.get('B3:B3', fields='userEnteredFormat.textFormat')[0][0]

# 提取字体家族
font_family = cell_format['userEnteredFormat']['textFormat'].get('fontFamily', '未设置')

# 提取字体颜色(转换为RGB格式)
color_info = cell_format['userEnteredFormat']['textFormat'].get('foregroundColor', {})
font_color = f"RGB({color_info.get('red', 0)*255:.0f}, {color_info.get('green', 0)*255:.0f}, {color_info.get('blue', 0)*255:.0f})"

print(f"字体: {font_family}")
print(f"字体颜色: {font_color}")

关键说明

  • fields='userEnteredFormat.textFormat':指定仅获取文本格式相关数据,避免返回冗余内容
  • userEnteredFormat.textFormat包含的常用属性:
    • fontFamily:字体名称
    • foregroundColor:字体颜色(以0-1的RGB小数存储)
    • fontSize:字体大小
    • bold/italic:加粗/斜体状态

如果需要获取更多格式属性,可扩展fields参数,例如fields='userEnteredFormat.textFormat,userEnteredFormat.backgroundColor'同时获取背景色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:55:19