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

Python操作Google Sheets:如何添加可执行的SUM汇总公式?

解决gspread写入Google Sheets时公式被自动添加单引号的问题

问题场景

我正在编写Python脚本,将Polars DataFrame上传至Google Sheets并做格式化处理,目标是在表格底部添加汇总行对各数值列求和。当前构建汇总行的代码如下:

# Add a summary row at the end of the data
num_rows = len(data)
total_row = ['Grand Total', ""]
for col in range(2, len(header)):
    total_formula = f'=SUM({chr(65 + col)}2:{chr(65 + col)}{num_rows})'
    total_row.append(total_formula)

new_sheet.append_row(total_row)

执行后发现生成的公式前被自动添加了单引号(例如'=SUM(F2:F47)),导致Google Sheets无法将其识别为可执行公式。

解决方案

问题根源在于gspread的append_row方法默认采用RAW输入模式,会把所有内容当作纯文本写入,因此给公式添加了单引号。只需在调用append_row时指定value_input_option='USER_ENTERED'参数,让Google Sheets以用户手动输入的逻辑解析内容,就能避免单引号并正常识别公式。

修改后的代码如下:

# Add a summary row at the end of the data
num_rows = len(data)
total_row = ['Grand Total', ""]
for col in range(2, len(header)):
    total_formula = f'=SUM({chr(65 + col)}2:{chr(65 + col)}{num_rows})'
    total_row.append(total_formula)

# 指定输入模式,确保公式被正确解析执行
new_sheet.append_row(total_row, value_input_option='USER_ENTERED')

补充说明

  • value_input_option的两个可选值:
    • 'RAW':默认值,将内容作为纯文本写入,会给公式添加单引号
    • 'USER_ENTERED':模拟用户手动输入的行为,Google Sheets会自动解析公式、格式等内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 15:57:07