Как узнать цвет ячейки в google sheet api?

Рейтинг: 0Ответов: 1Опубликовано: 01.02.2023

Читал документацию, ничего не нашел, видел подобный тред на англо-язычном stackoverflow, но не понял как реализовать. Мне нужно чтобы скрипт парсил ячейки, например: A1:A2, и если в этом диапазоне будет ячейка красного цвета - в консоли напишет "2", если любой другой то "1".

Моя попытка это реализовать:

from pprint import pprint
import os
from google.oauth2.credentials import Credentials
from googleapiclient import discovery
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
SAMPLE_SPREADSHEET_ID = '#'
SAMPLE_RANGE_NAME = 'A1:A2'
creds = None

if os.path.exists('token.json'):
   creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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)
   with open('token.json', 'w') as token:
      token.write(creds.to_json())
service = discovery.build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
                     range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])

request = service.spreadsheets().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, ranges=SAMPLE_RANGE_NAME, includeGridData=include_grid_data)
   response = request.execute()

for row in values:
   if response['sheets'][0]['data'][0]['rowData'][0]['values'][0]['effectiveFormat']['backgroundColor'] == {'red': 1, 'green': 1, 'blue': 1}:
        print("1")

Вот так выглядит переменная response:

{'properties': {'autoRecalc': 'ON_CHANGE',
                'defaultFormat': {'backgroundColor': {'blue': 1,
                                                      'green': 1,
                                                      'red': 1},
                                  'backgroundColorStyle': {'rgbColor': {'blue': 1,
                                                                        'green': 1,
                                                                        'red': 1}},
                                  'padding': {'bottom': 2,
                                              'left': 3,
                                              'right': 3,
                                              'top': 2},
                                  'textFormat': {'bold': False,
                                                 'fontFamily': 'arial,sans,sans-serif',
                                                 'fontSize': 10,
                                                 'foregroundColor': {},
                                                 'foregroundColorStyle': {'rgbColor': {}},
                                                 'italic': False,
                                                 'strikethrough': False,
                                                 'underline': False},
                                  'verticalAlignment': 'BOTTOM',
                                  'wrapStrategy': 'OVERFLOW_CELL'},
                'locale': 'ru_RU',
                'spreadsheetTheme': {'primaryFontFamily': 'Arial',
                                     'themeColors': [{'color': {'rgbColor': {}},
                                                      'colorType': 'TEXT'},
                                                     {'color': {'rgbColor': {'blue': 1,
                                                                             'green': 1,
                                                                             'red': 1}},
                                                      'colorType': 'BACKGROUND'},
                                                     {'color': {'rgbColor': {'blue': 0.95686275,
                                                                             'green': 0.52156866,
                                                                             'red': 0.25882354}},
                                                      'colorType': 'ACCENT1'},
                                                     {'color': {'rgbColor': {'blue': 0.20784314,
                                                                             'green': 0.2627451,
                                                                             'red': 0.91764706}},
                                                      'colorType': 'ACCENT2'},
                                                     {'color': {'rgbColor': {'blue': 0.015686275,
                                                                             'green': 0.7372549,
                                                                             'red': 0.9843137}},
                                                      'colorType': 'ACCENT3'},
                                                     {'color': {'rgbColor': {'blue': 0.3254902,
                                                                             'green': 0.65882355,
                                                                             'red': 0.20392157}},
                                                      'colorType': 'ACCENT4'},
                                                     {'color': {'rgbColor': {'blue': 0.003921569,
                                                                             'green': 0.42745098,
                                                                             'red': 1}},
                                                      'colorType': 'ACCENT5'},
                                                     {'color': {'rgbColor': {'blue': 0.7764706,
                                                                             'green': 0.7411765,
                                                                             'red': 0.27450982}},
                                                      'colorType': 'ACCENT6'},
                                                     {'color': {'rgbColor': {'blue': 0.8,
                                                                             'green': 0.33333334,
                                                                             'red': 0.06666667}},
                                                      'colorType': 'LINK'}]},
                'timeZone': 'Europe/Bucharest',
                'title': '#'},
 'sheets': [{'data': [{'columnMetadata': [{'pixelSize': 181}],
                       'rowData': [{'values': [{'effectiveFormat': {'backgroundColor': {'red': 1},
                                                                    'backgroundColorStyle': {'rgbColor': {'red': 1}},
                                                                    'horizontalAlignment': 'LEFT',
                                                                    'hyperlinkDisplayType': 'PLAIN_TEXT',
                                                                    'padding': {'bottom': 2,
                                                                                'left': 3,
                                                                                'right': 3,
                                                                                'top': 2},
                                                                    'textFormat': {'bold': False,
                                                                                   'fontFamily': 'Arial',
                                                                                   'fontSize': 10,
                                                                                   'foregroundColor': {},
                                                                                   'foregroundColorStyle': {'rgbColor': {}},
                                                                                   'italic': False,
                                                                                   'strikethrough': False,
                                                                                   'underline': False},
                                                                    'verticalAlignment': 'BOTTOM',
                                                                    'wrapStrategy': 'OVERFLOW_CELL'},
                                                'effectiveValue': {'stringValue': '#'},
                                                'formattedValue': '#',
                                                'userEnteredFormat': {'backgroundColor': {'red': 1},
                                                                      'backgroundColorStyle': {'rgbColor': {'red': 1}}},
                                                'userEnteredValue': {'stringValue': '#'}}]},
                                   {'values': [{'effectiveFormat': {'backgroundColor': {'blue': 1,
                                                                                        'green': 1,
                                                                                        'red': 1},
                                                                    'backgroundColorStyle': {'rgbColor': {'blue': 1,
                                                                                                          'green': 1,
                                                                                                          'red': 1}},
                                                                    'horizontalAlignment': 'LEFT',
                                                                    'hyperlinkDisplayType': 'PLAIN_TEXT',
                                                                    'padding': {'bottom': 2,
                                                                                'left': 3,
                                                                                'right': 3,
                                                                                'top': 2},
                                                                    'textFormat': {'bold': False,
                                                                                   'fontFamily': 'Arial',
                                                                                   'fontSize': 10,
                                                                                   'foregroundColor': {},
                                                                                   'foregroundColorStyle': {'rgbColor': {}},
                                                                                   'italic': False,
                                                                                   'strikethrough': False,
                                                                                   'underline': False},
                                                                    'verticalAlignment': 'BOTTOM',
                                                                    'wrapStrategy': 'OVERFLOW_CELL'},
                                                'effectiveValue': {'stringValue': '#'},
                                                'formattedValue': '#',
                                                'userEnteredValue': {'stringValue': '#'}}]}],
                       'rowMetadata': [{'pixelSize': 21}, {'pixelSize': 21}],
                       'startRow': 5}],
             'properties': {'gridProperties': {'columnCount': 26,
                                               'rowCount': 883},
                            'index': 1,
                            'sheetId': 1719419176,
                            'sheetType': 'GRID',
                            'title': '#'}}],
 'spreadsheetId': '#',
 'spreadsheetUrl': '#'}

Как я понимаю моя ошибка находится в сравнении этой переменной, если быть точнее то конкретно в этом месте кода:

for row in values:
   if response['sheets'][0]['data'][0]['rowData'][0]['values'][0]['effectiveFormat']['backgroundColor'] == {'red': 1, 'green': 1, 'blue': 1}:
        print("1")

Ибо в итоге оно выдает одно и тоже значение. Спасибо за прочтение :>

Ответы

▲ 0

На примере js

const color = (response.sheets[0].data[0].rowData[0].values[0].userEnteredFormat.backgroundColor);
  
  if ( color.red == 1 ) console.log('Цвет ячейки - красный')
  else if ( color.green == 1 ) {
    console.log('Цвет ячейки - зеленый')