使用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
相关产品推荐
相关产品推荐

