代碼如下。這不是完整的代碼,而是它的基礎。我正在嘗試從 Twitter 的 API 獲取資料并將其寫入我的 Google Sheets API。以下是代碼。
from googleapiclient import discovery
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE = 'twitter.json' #json File should be in the same folder as this Python Script.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg'
#SAMPLE_RANGE_NAME = 'Class Data!A2:A60'
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# Call the Sheets API
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range='twitterData!A1:A180').execute()
#ERROR HERE BELOW
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
我收到錯誤的一行在其上方的錯誤下方有評論。這是錯誤訊息:
Traceback (most recent call last):
File "C:\Users\John Doe\Desktop\Code\Python\Twitter\test.py", line 27, in <module>
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\John Doe\AppData\Local\Programs\Python\Python38-32\lib\site-packages\googleapiclient\http.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg/values/twitterData!B2:B180?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data.values', 'description': "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"}]}]">
我以前使用過 Google Sheets API。我不確定為什么這段代碼不起作用。它只是那一行。
uj5u.com熱心網友回復:
我認為您當前問題的原因"Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"
是由于body={"values": 8}
。在這種情況下,需要使用二維陣列。所以,請修改如下。
從:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
至:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID, range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": [[8]]}).execute()
- 在本次修改中,
body={"values": 8}
被修改為body={"values": [[8]]}
. - 通過此修改,
8
將被放入“twitterData”作業表的單元格“B2”。
參考:
- 方法:電子表格.values.update
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/537471.html
標籤:Google Cloud Collective Python谷歌表格谷歌云平台google-sheets-api