我可以使用 gspread 批量更新电子表格中的多个工作表吗?

Can I batch update multiple worksheet in a spreadsheet using gspread?

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)

s0.batch_update([
    {'range': 'A3', 'values':fin_5min},
    {'range': 'D3', 'values': fin_15min}
])

我想用与 s0 相同的数据更新 s1 sheet。如何使用 gspread 在单个请求中执行此操作?

问题和解决方法:

在Sheets API,我认为通过spreadsheets.values.batchUpdate的方法可以达到你的目的。但遗憾的是,在目前阶段,gspread似乎并没有包含这个方法。因此,作为一种解决方法,我想建议使用使用 requests 模块的方法。

当你的脚本修改后,变成如下。

修改后的脚本:

client = gspread.authorize(creds)
sh = client.open("kite")

sheetTitles = [sh.get_worksheet(0).title, sh.get_worksheet(1).title]
values = [{'range': 'A3', 'values': fin_5min}, {'range': 'D3', 'values': fin_15min}]
reqs = [[{'range': "'" + t + "'!" + v['range'], 'values': v['values']} for v in values] for t in sheetTitles]
res = requests.post(
    'https://sheets.googleapis.com/v4/spreadsheets/' + sh.id + '/values:batchUpdate',
    headers={"Authorization": "Bearer " + creds.get_access_token().access_token, "Content-Type": "application/json"}, # modified
    data=json.dumps({"data": sum(reqs, []), "valueInputOption": "USER_ENTERED"})
)
  • client = gspread.authorize(creds)creds 检索访问令牌。
  • 在这种情况下,fin_5minfin_15min的值需要是二维数组。请注意这一点。
  • 通过上面的修改,values的值被放到第1张和第2张。
  • 并且,在此修改后的脚本中,请添加 import requestsimport json

参考: