如何通过 Python 中的 Google Sheets API v4 调用电子表格中的特定工作表

Rem*_*den 4 python google-sheets python-3.x google-sheets-api

我对这些东西很陌生,而且我在我的早期项目中真的遇到了麻烦。

我已经尽最大努力到处寻找,包括 - 搜索引擎、StackOverflow、API 文档,但我真的找不到任何地方的答案。所以我希望提问是合适的。

我正在尝试从 Google 工作表的特定工作表(底部的标签)查看范围。我知道这张表有一个可以在 url 中找到的 sheetId。我可以得到这个,但是,我绝对找不到使用此编号请求特定工作表的方法。我找到了使用这个数字来复制和复制工作表的方法,我什至找到了一种在电子表格上打印所有可用 sheetId 的方法。

def suggestion():

SAMPLE_SPREADSHEET_ID = 'mySpreadsheetID'
SAMPLE_RANGE_NAME = 'A1:D12'

"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
    flow = client.flow_from_clientsecrets('creds.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))

# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                            range=SAMPLE_RANGE_NAME,).execute()
values = result.get('values', [])

if not values:
    print('No data found.')
else:
    for row in values:
        # Print columns A and E, which correspond to indices 0 and 4.
        print(row)
Run Code Online (Sandbox Code Playgroud)

我相信答案可能在这里https://developers.google.com/resources/api-libraries/documentation/sheets/v4/python/latest/sheets_v4.spreadsheets.values.html但我似乎找不到它.

现在程序正在打开默认工作表(底部的选项卡),当我希望它打开其中一个特定工作表并在那里查找数据时。

提前感谢您的任何帮助。它的大规模赞赏!

mr.*_*eze 6

Google 表格使用A1 表示法来指定范围。这可以包括您尝试从中访问值的特定选项卡。

您可以通过在范围之前添加工作表的名称来指定范围值中的选项卡。例如,如果您想要 Sheet2 中的某些内容:

SAMPLE_RANGE = 'Sheet2!A2:E10'
Run Code Online (Sandbox Code Playgroud)

如果您重命名您的工作表标签,那么您需要更新您的范围以匹配它,因为它是按名称引用的。