Home » excel » python – Get Excel cell background color in pandas read_excel?

python – Get Excel cell background color in pandas read_excel?

Posted by: admin March 9, 2020 Leave a comment

Questions:

I have an Excel file with cells having background colors. I am reading that file into pandas with read_excel. Is there any way to get the background colors of cells?

How to&Answers:

Brute-forced it through xlrd, as per Mark‘s suggestion:

from xlrd import open_workbook
wb = open_workbook('wb.xls', formatting_info=True)
sheet = wb.sheet_by_name("mysheet")
#create empy colormask matrix
bgcol=np.zeros([sheet.nrows,sheet.ncols])
#cycle through all cells to get colors
for row in range(sheet.nrows):
  for column in range(sheet.ncols):
    cell = sheet.cell(row, column)  
    fmt = wb.xf_list[cell.xf_index]
    bgcol[row,column]=fmt.background.background_colour_index
#return pandas mask of colors
colormask=pd.DataFrame(bgcol) 

Yet, there must be a better way thorugh pandas directly…

Answer:

I edited the code snippet from @csaladenes’s response above based on this link, and it works for my xls file (the original resulted in all cells showing the same color index, though they have different background colors):

import xlrd
import numpy as np
wb = xlrd.open_workbook(file, formatting_info=True)
sheet = wb.sheet_by_name("mysheet")
bgcol=np.zeros([sheet.nrows,sheet.ncols])
for row in range(sheet.nrows):
    for col in range(sheet.ncols):
        c = sheet.cell(row, col)
        cif = sheet.cell_xf_index(row, col)
        iif = wb.xf_list[cif]
        cbg = iif.background.pattern_colour_index
        bgcol[row,col] = cbg