Madhu
Madhu

Reputation: 65

In a Excel file how to find the background color of a cell using openpyxl (Python)

`wb = openpyxl.load_workbook('file.xlsx',data_only=True)
fs_count_row = fs.max_row 
fs_count_col = fs.max_column 
for a in range(1,fs_count_row):
    cell_color = fs.cell(column=1, row=a)
    bgColor = cell_color.fill.bgColor.index
    fgColor = cell_color.fill.fgColor.index`

Tried using the above code. However, it works fine for some cells and give wrong output for some other cells. Can I know the reason why?

Upvotes: 0

Views: 8510

Answers (1)

Dinesh
Dinesh

Reputation: 51

Column number was fixed to 1 always, that's why code is not picking up the cells outside of the first column. Loop both rows and columns. Updated code below. I've added a print statement to provide the fgcolor and bgcolor of all the active cells along with the cell information. In addition, I've added a condition to ignore the blank cells where there is no foreground or background color.

Input:

Cell A1 = Yellow
Cell A2 = Blank
Cell B1 = Black
Cell B2 = Red

Code:

import openpyxl
wb = openpyxl.load_workbook('Excel.xlsx',data_only=True)
fs = wb.active
fs_count_row = fs.max_row 
fs_count_col = fs.max_column 
for row in range(1,fs_count_row+1):
    for column in range(1,fs_count_col+1):
        cell_color = fs.cell(column=column, row=row)
        bgColor = cell_color.fill.bgColor.index
        fgColor = cell_color.fill.fgColor.index
        if (bgColor=='00000000') or (fgColor=='00000000'):
            continue
        else:
            print("Background color index of cell (",row,column, ") is", bgColor)
            print("Foreground color index of cell (",row,column, ") is", fgColor)

Output:

Background color index of cell ( 1 1 ) is 64
Foreground color index of cell ( 1 1 ) is FFFFFF00
Background color index of cell ( 1 2 ) is 64
Foreground color index of cell ( 1 2 ) is 1
Background color index of cell ( 2 2 ) is 64
Foreground color index of cell ( 2 2 ) is FFFF0000

Upvotes: 4

Related Questions