Я пытаюсь прочитать данные из электронной таблицы Google, используя Python 3. Все мои таблицы имеют несколько листов. Мне нужно получить все данные только с отдельных листов, в заголовке которых есть «Журнал».
Я нашел только примеры обработки электронной таблицы с одним листом «Лист1». Ниже приведен код, который я могу распечатать имена листов, заголовок которых начинается с «Журнал». Однако я не вижу, как прочитать все строки и сделать что-нибудь полезное с этими данными.
#! /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()