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

Windows10下Python调用Google Sheets API读取/编辑Sheet2失败求助

解决gspread无法访问Google Sheets中Sheet2及后续工作表的问题

嘿,我来帮你搞定这个问题!你遇到的情况其实是gspread库的一个小细节导致的,咱们一步步来解决:

问题根源

gspread为了方便操作,只给第一个工作表提供了.sheet1这个快捷访问属性,但并没有自动生成.sheet2、.sheet3这类对应后续工作表的属性——所以直接写.sheet2肯定会报错啦!

正确的访问方式

你可以通过以下几种方法来访问Sheet2或其他自定义工作表:

1. 通过工作表名称获取(推荐)

直接使用工作表的实际标签名(比如你的Sheet2如果改了名字,就用新名字):

penny = client.open('pennystocks').worksheet('Sheet2')

2. 通过索引获取

工作表的索引从0开始计数:

  • Sheet1对应索引0
  • Sheet2对应索引1
  • Sheet3对应索引2,以此类推

代码示例:

penny = client.open('pennystocks').get_worksheet(1)

3. 获取所有工作表列表后选择

先获取文档中所有工作表的列表,再通过索引选择:

# 获取所有工作表
all_sheets = client.open('pennystocks').worksheets()
# 选择第二个工作表(索引1)
penny = all_sheets[1]

修改后的完整代码示例

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('client_penny.json', scope)
client = gspread.authorize(creds)

# 用工作表名称访问Sheet2(替换成你的实际工作表名)
penny = client.open('pennystocks').worksheet('Sheet2')
# 验证读取功能
print(penny.get_all_records())

额外注意事项

  • 确保你在Google Sheets文档中已经把服务账号(就是你JSON密钥里的邮箱)添加为协作者,权限设置为“编辑”或“查看”(根据你的需求)——不过既然你能访问Sheet1,这一步应该已经搞定了。
  • 如果工作表的标签名有空格或特殊字符,要完整输入,比如worksheet('我的数据表')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:09:26