I have a table, there are many data cells in it. Some cells have a color, say yellow.
How can you find these colored cells and find out what they contain?
I have a table, there are many data cells in it. Some cells have a color, say yellow.
How can you find these colored cells and find out what they contain?
openpyxl (works with .XLSX files).
Original file:
from openpyxl import load_workbook wb = load_workbook('c:/temp/a.xlsx') sh = wb['Sheet1'] print('background colors for ALL cells:\n') for row in sh.iter_rows(): for cell in row: print(f'[{cell.coordinate}]: {cell.fill.fgColor.value}', end=' ') print() def find_cells_by_color(sh, color='00000000'): ret = {} for row in sh.iter_rows(): for cell in row: if cell.fill.fgColor.value == color: ret[cell.coordinate] = cell.value return ret res = find_cells_by_color(sh, color='FFFFFF00') print(f'given color has been found in the following cells: {res}') Conclusion:
background colors for ALL cells: [A1]: 00000000 [B1]: 00000000 [C1]: 00000000 [A2]: FFFFFF00 [B2]: 00000000 [C2]: FFFF0000 [A3]: 00000000 [B3]: FFFFFF00 [C3]: FFFFFF00 [A4]: 00000000 [B4]: 00000000 [C4]: FF00B050 given color has been found in the following cells: {'A2': 1, 'B3': 5, 'C3': 6} PS I did not find a simple way to determine the color code by name, so I went empirically ...
a , i.e. alpha channel indicates what transparency the color will have - gil9redFor Windows OS through the COM object, this is most conveniently done, and there is no need to pull additional libraries and modules, Python + VBA:
# -*- coding: utf-8 -*- import win32com.client Excel = win32com.client.Dispatch("Excel.Application") wb = Excel.Workbooks.Open(u'D:\\xl.xlsx') sheet = wb.ActiveSheet var = 0 for row in range(1, 5): for column in range(1, 5): # Поиск по индексу цвета ColorIndex. Если по цвету, то Color if sheet.Cells(row, column).Interior.ColorIndex == 6: var += sheet.Cells(i, j).Value print(var) wb.Save() wb.Close() Excel.Quit() не надо дополнительных библиотек и модулей тянуть but only on windows and it will work :) - gil9redYou can use xlrd go through all the cells, get their color and look for the one you need with if :
import xlrd book = xlrd.open_workbook("sample.xls", formatting_info=True) sheets = book.sheet_names() for index, sh in enumerate(sheets): sheet = book.sheet_by_index(index) rows, cols = sheet.nrows, sheet.ncols for row in range(rows): for col in range(cols): xfx = sheet.cell_xf_index(row, col) xf = book.xf_list[xfx] bgx = xf.background.pattern_colour_index #Цвет фона rgb = book.colour_map[bgx] #Цвет в RGB формате thecell = sheet.cell(row, col) print thecell.value #Значение данной ячейки NotImplementedError: formatting_info=True not yet implemented - MaxUSource: https://ru.stackoverflow.com/questions/845286/
All Articles