我想復制"'data'!A2:D2"到,"'data'!K2:N2"但出現以下錯誤。該腳本適用于批量更新,但無法通過復制和粘貼來解決。
{"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"requests\": Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"@type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"requests\": Cannot find field."
}]}]}}
我正在使用的代碼。
import json
import gspread
import requests
from oauth2client.service_account import ServiceAccountCredentials
scope = [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive",
]
creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
client = gspread.authorize(creds)
sh = client.open("kite")
spreadsheet_id = sh.id
sheet_id = sh.worksheet("data").id
headers = {
"Authorization": "Bearer " creds.get_access_token().access_token,
"Content-Type": "application/json",
}
reqs = [
{
"copyPaste": {
"source": {
"sheetId": sheet_id,
"startRowIndex": 1,
"endRowIndex": 2,
"startColumnIndex": 0,
"endColumnIndex": 4,
},
"destination": {
"sheetId": sheet_id,
"startRowIndex": 1,
"endRowIndex": 2,
"startColumnIndex": 10,
"endColumnIndex": 14,
},
"pasteType": "PASTE_VALUES",
"pasteOrientation": "NORMAL",
}
}
]
r = requests.post(
f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values:batchUpdate",
headers=headers,
data=json.dumps({"requests": reqs}),
)
參考: https ://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request#CopyPasteRequest
uj5u.com熱心網友回復:
copyPaste 請求可以與電子表格.batchUpdate 方法一起使用。因此,當您的腳本被修改時,請進行如下修改。
從:
f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}/values:batchUpdate",
到:
f"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheet_id}:batchUpdate",
筆記:
在您的腳本中,使用了 gspread。當使用 gspread 時,您的腳本也可以進行如下修改。
client = gspread.authorize(creds) sh = client.open("kite") sheet_id = sh.worksheet("data").id reqs = [ { "copyPaste": { "source": { "sheetId": sheet_id, "startRowIndex": 1, "endRowIndex": 2, "startColumnIndex": 0, "endColumnIndex": 4, }, "destination": { "sheetId": sheet_id, "startRowIndex": 1, "endRowIndex": 2, "startColumnIndex": 10, "endColumnIndex": 14, }, "pasteType": "PASTE_VALUES", "pasteOrientation": "NORMAL", } } ] res = sh.batch_update({"requests": reqs})
參考:
- 方法:電子表格.batchUpdate
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438798.html
