python-3.x - 如何使用 python 3 遍历 google 工作表中的所有工作表?

标签 python-3.x google-sheets scripting

我正在尝试使用 Python 3 从 Google 电子表格中读取数据。我的所有电子表格都有多个工作表。 我只需要从标题中包含“日志”的各个工作表中获取所有数据。

我只找到了使用名为“Sheet1”的单个工作表处理电子表格的示例。 下面是我的代码,它能够打印标题以“日志”开头的工作表的名称。但是,我看不到如何读取所有行并对这些数据做一些有用的事情。

#! /usr/bin/env python3
# -*- mode: python; coding: utf-8 -*-

import os.path
import pickle
import re
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']

my_spreadsheets = ['sheet id goes here',  # add more spreadsheet ids after the code works for one SS.         
    ]

def get_creds():
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('sheets', 'v4', credentials=creds)
    return service    

def main():
    service = get_creds()
    # Iterate over the list of spreadsheets (spreadsheet Ids)
    log_RE = re.compile('^Log ')
    for spreadsheetId in my_spreadsheets:
        sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheetId).execute()
        sheets = sheet_metadata.get('sheets', '')
        # Iterate over each of the sheets.
        for sheet in sheets:
          title = sheet.get("properties", {}).get("title", "Sheet1")
          if re.search(log_RE, title):
            sheet_id = sheet.get("properties", {}).get("sheetId", 0)
            print(title)
             # read all the rows in the sheet and process them here
             # process the data from all the rows and do something useful here.

if __name__ == "__main__":
    main()

最佳答案

需要以下代码来迭代和读取所选工作表:

          if re.search(log_RE, title):
            rangeName = title + '!A:Z'
            sheet_id = sheet.get("properties", {}).get("sheetId", 0)
            request = service.spreadsheets().values().get(spreadsheetId=spreadsheetId, range=rangeName)
            response = request.execute()

因此,使用 get 读取电子表格,为其提供 spreadsheedId 和工作表名称,这是范围的一部分。

关于python-3.x - 如何使用 python 3 遍历 google 工作表中的所有工作表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59915787/

相关文章:

google-sheets - Google 表格中财务数据的自定义聚合

date - Google Sheets FILTER 公式大于 TODAY()

shell - = : This is not an identifier

python - 如何使用一两行检查 Python 列表仅包含 True,然后仅包含 False?

Python RAM写入和读取

python - 从文件末尾寻找抛出不受支持的异常

google-apps-script - 与其他用户共享 Google App 脚本 - 请求权限并授权脚本

linux - 使用 Ctrl+C 杀死从 Bash 脚本运行的 Java 应用程序进程树

bash 脚本参数

python - 如何并行文件下载?