通过 Google Sheets API 和 Python 读取 Sheet2

Bik*_*rth 2 python google-api

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

选项卡示例:https://i.stack.imgur.com/d4Ee9.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())
Run Code Online (Sandbox Code Playgroud)

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

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

Tan*_*ike 5

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

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

从:

penny = client.open('pennystocks').sheet1
Run Code Online (Sandbox Code Playgroud)

到:

penny = client.open('pennystocks').worksheet('Sheet2')
Run Code Online (Sandbox Code Playgroud)

笔记:

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

参考:

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