首页 > 解决方案 > 通过 Google Sheets API 和 Python 阅读 Sheet2

问题描述

我只想通过我的 Google Sheets Project with Python (Windows 10) 中的 API 阅读下一个选项卡/工作表,一切都适用于 sheet1,我只想阅读/编辑 sheet2(以及我将在项目中创建的其他内容)。

标签示例:https ://i.imgur.com/260rI7K.jpg

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)

penny = client.open('pennystocks').sheet1

print(penny.get_all_records())

这有效:penny = client.open('pennystocks').sheet1

这不会: penny = client.open('pennystocks').sheet2

标签: pythongoogle-api

解决方案


  • 您希望使用 gspread 使用除第一个选项卡之外的工作表。
    • 例如,当电子表格中有 2 张“Sheet1”和“Sheet2”时,您想使用“Sheet2”。

如果我的理解是正确的,那么这个修改呢?

从:

penny = client.open('pennystocks').sheet1

至:

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

笔记:

  • client.open('pennystocks').sheet1是打开工作表的第一个索引。例如,在您的电子表格中,当“Sheet1”的索引修改为“Sheet2”时,client.open('pennystocks').sheet1返回“Sheet2”。

参考:

如果我误解了您的问题并且这不是您想要的结果,我深表歉意。


推荐阅读