You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Google Sheets API报'Resource'无'service'属性如何解决

错误原因

你报错是因为API对象调用路径错误:代码里你已经通过sheet = service.spreadsheets()将spreadsheets资源对象赋值给了sheet变量,调用update方法时不需要再额外加.service.spreadsheets(),sheet对象本身没有service属性,所以触发了AttributeError。
另外你的写入值格式也不符合API要求,后续执行会出现第二个报错:Google Sheets API要求写入的values参数是二维列表结构(外层列表代表行,内层列表代表该行的每个单元格值),你写的[("present")]实际等效于一维列表["present"],不符合接口要求。

修正步骤
  • 调整update方法的调用路径,删除多余的.service.spreadsheets()段
  • 调整写入值的结构为标准二维列表
修正后完整代码
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 = service_account.Credentials.from_service_account_file(
       SERVICE_ACCOUNT_FILE, scopes=SCOPES)

# 电子表格ID
SAMPLE_SPREADSHEET_ID = '14uNIk1Q_jNKRL-yuz5Fssu3iVsQzmYf6wHXZDnjWkW0'

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

# 调用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"]]

# 调整调用路径,直接用sheet.values().update
request = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                           range="Sheet2!A1", valueInputOption="USER_ENTERED", body={"values":value_for_write}).execute()

print(values)

内容的提问来源于stack exchange,提问作者Scarlett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:54:03