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

使用gspread能否单次请求批量更新电子表格内的多个工作表?

要在单次请求中批量更新同一电子表格下的多个工作表,不需要在单个工作表对象上调用batch_update,直接调用**电子表格实例(你代码中的sh)**的batch_update方法即可,在每个更新项的range参数中加上工作表名前缀即可匹配不同工作表。

修改后的代码如下:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]

creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)

sh = client.open("kite")
s0 = sh.get_worksheet(0)
s1 = sh.get_worksheet(1)

# 直接在电子表格实例上调批量更新,所有操作打包为单次请求
sh.batch_update([
    # 写入第一个工作表
    {'range': f"{s0.title}!A3", 'values': fin_5min},
    {'range': f"{s0.title}!D3", 'values': fin_15min},
    # 写入第二个工作表,数据和第一个完全一致
    {'range': f"{s1.title}!A3", 'values': fin_5min},
    {'range': f"{s1.title}!D3", 'values': fin_15min}
])

注意事项

  • 若工作表名称包含空格、特殊字符,需要将表名用单引号包裹,格式为f"'{s0.title}'!A3"
  • 该方式调用的是谷歌表格原生的spreadsheets.values.batchUpdate接口,所有更新操作仅触发1次API请求,不会额外占用接口配额。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 16:06:03