如何解决 'Resource' object has no attribute 'service' " in python , google api

how to solve "'Resource' object has no attribute 'service' " in python , google api

我正在尝试使用 google api 制作一个项目。在那个项目中,我给出了一个字符串,python 脚本应该 change/modify google sheet 中的一个单元格,并更改该字符串的单元格的值。但是问题是有错误-

request = sheet.service.spreadsheets().values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, AttributeError: 'Resource' object has no attribute 'service' 我该怎么办?

这是代码-

from __future__ import print_function
from googleapiclient.discovery import build

from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE = 'python-sheets-keys.json'
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
       SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# If modifying these scopes, delete the file token.json.

# The ID of the spreadsheet.
SAMPLE_SPREADSHEET_ID = '14uNIk1Q_jNKRL-yuz5Fssu3iVsQzmYf6wHXZDnjWkW0'


service = build('sheets', 'v4', credentials=creds)

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,                           range="test!A1:B10").execute()
values = result.get('values', [])

value_for_write = [("present")]

request = sheet.service.spreadsheets().values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                           range="Sheet2!A1", valueInputOption="USER_ENTERED", body={"values":value_for_write}).execute()

print(values)

修改如下如何?

发件人:

value_for_write = [("present")]

request = sheet.service.spreadsheets().values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                           range="Sheet2!A1", valueInputOption="USER_ENTERED", body={"values":value_for_write}).execute()

收件人:

value_for_write = [["present"]]
request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range="Sheet2!A1", valueInputOption="USER_ENTERED", body={"values":value_for_write}).execute()
  • 在您的脚本中,使用了 sheet = service.spreadsheets()。所以我用了。
  • value_for_write of {"values":value_for_write} for sheet.values().update 需要是二维数组。

参考: