【问题标题】:How to call a specific sheet within a spreadsheet via the Google Sheets API v4 in Python如何通过 Python 中的 Google Sheets API v4 调用电子表格中的特定工作表
【发布时间】:2019-04-20 12:33:21
【问题描述】:

我对这些东西还很陌生,而且我在我的早期项目中确实碰壁了。

我已尽我所能到处寻找,包括 - 搜索引擎、StackOverflow、API 文档,但我真的无法在任何地方找到答案。所以我希望它适合问。

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

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

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

提前感谢您的帮助。非常感谢!

【问题讨论】:

    标签: python python-3.x google-sheets google-sheets-api


    【解决方案1】:

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

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

    SAMPLE_RANGE = 'Sheet2!A2:E10'
    

    如果重命名工作表选项卡,则需要更新范围以匹配它,因为它是按名称引用的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2017-04-18
      • 2018-09-21
      • 1970-01-01
      相关资源
      最近更新 更多