gspread batch_update导入CSV报错:未知字段SheetId
问题描述
我使用gspread库,尝试通过batch_update(body)方法将CSV数据更新到Google Sheets,但执行sh.batch_update(body)时遇到APIError,错误提示为:Invalid JSON payload received. Unknown name "SheetId" at 'requests[0].paste_data.coordinate'。此前用gc.import_csv(spreadsheet_id,content)可以完成导入,但该方法会删除其他工作表并重命名目标工作表,不符合需求,求助解决该报错。
错误回溯
Traceback (most recent call last): File "C:\pyscrpts\mytest.py", line 76, in main sh.batch_update(body) File "C:\Users\\AppData\Roaming\Python\Python39\site-packages\gspread\spreadsheet.py", line 131, in batch_update r = self.client.request( File "C:\Users\ \AppData\Roaming\Python\Python39\site-packages\gspread\client.py", line 92, in request raise APIError(response) gspread.exceptions.APIError: {'code': 400, 'message': 'Invalid JSON payload received. Unknown name "SheetId" at \'requests[0].paste_data.coordinate\': Cannot find field.', 'status': 'INVALID_ARGUMENT', 'details': [{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'requests[0].paste_data.coordinate', 'description': 'Invalid JSON payload received. Unknown name "SheetId" at \'requests[0].paste_data.coordinate\': Cannot find field.'}]}]}
我的代码
from __future__ import print_function from datetime import date, timedelta import pickle import logging import os.path import argparse import sys import socket from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2 import service_account import google.auth.transport.requests import requests import gspread # gspread way ************ # authenticate to Google Sheets with a service account credentials json file # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] #SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] SPREADSHEET_ID = '11G6hTgQ3nrVDQQj94BR5zeXvK453454sdfsfdsfdsd' base = "C:/pyscrpts/" # CREDS FILE FOR GSPREAD gc = gspread.service_account(filename= 'c:\pyscrpts\creds.json') csv_file_path = base + 'updates.csv' SERVICE_ACCOUNT_FILE = 'c:\pyscrpts\creds.json' credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE,scopes=SCOPES) def main(): #logging.basicConfig(filename='errorlog.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s') # Creating an object #logger=logging.getLogger(__name__) # Setting the threshold of logger to DEBUG #logger.setLevel(logging.DEBUG) creds = None service = build('sheets', 'v4', SERVICE_ACCOUNT_FILE) sh = gc.open_by_key(SPREADSHEET_ID) ws = sh.sheet1 #clear worksheet ws.clear() ) content = open(csv_file_path,'r', encoding='utf-8').read() gc.import_csv(SPREADSHEET_ID,content) #Read csv and form request with open(csv_file_path, 'r', encoding='UTF8') as csv_file: csvContents = csv_file.read() body = { 'requests': [{ 'pasteData': { "coordinate": { "SheetId": SPREADSHEET_ID, "rowIndex": "0", "columnIndex": "0", }, "data": csvContents, "type": 'PASTE_NORMAL', "delimiter": ',', } }] } sh.batch_update(body) #requests = service.spreadsheets().batchUpdate(spreadsheetId=SPREADSHEET_ID, body=body) #response = requests.execute() if __name__ == '__main__': main()
解决方案
报错核心原因是pasteData.coordinate的字段名和取值错误,同时还有其他几处代码问题,修正如下:
- 字段名修正:
coordinate里的字段应该是小写的sheetId,而非大写开头的SheetId;且取值不能填表格ID,要填目标工作表的ID(可通过ws.id获取)。 - 数据类型修正:
rowIndex和columnIndex需为整数类型,不能用字符串。 - 权限范围修正:将只读权限
spreadsheets.readonly改为可读写权限https://www.googleapis.com/auth/spreadsheets。 - 冗余代码清理:删除代码中多余的
),以及不需要的gc.import_csv调用。
修正后的核心代码片段:
# 修改权限范围为可读写 SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] def main(): sh = gc.open_by_key(SPREADSHEET_ID) ws = sh.sheet1 ws.clear() with open(csv_file_path, 'r', encoding='UTF8') as csv_file: csvContents = csv_file.read() # 获取目标工作表的ID sheet_id = ws.id body = { 'requests': [{ 'pasteData': { "coordinate": { "sheetId": sheet_id, # 小写字段名+工作表ID "rowIndex": 0, # 整数类型 "columnIndex": 0, # 整数类型 }, "data": csvContents, "type": 'PASTE_NORMAL', "delimiter": ',', } }] } sh.batch_update(body)
内容的提问来源于stack exchange,提问作者maggiemay
相关产品推荐
相关产品推荐

