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}
])
我想s1用與s0. 如何使用 gspread 在單個請求中執行此操作?
uj5u.com熱心網友回復:
問題和解決方法:
在 Sheets API,我認為您的目標可以通過電子表格.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"})
)
- 訪問令牌是從
credsof檢索的client = gspread.authorize(creds)。 - 在這種情況下,值
fin_5min和fin_15min需要是2維陣列。請注意這一點。 - 通過上述修改,將 的值
values放入第一張和第二張。 - 并且,在這個修改后的腳本中,請添加
import requests和import json。
參考:
- 方法:spreadsheets.values.batchUpdate
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350486.html
標籤:谷歌表格 google-sheets-api gspread
