Search code examples
pythonxlrd

Count the number of cells with red text in excel file using xlrd in python


I am using xlrd to open an excel file in my computer and I have numbers in red, numbers in black, I want to count the number of numbers in red, do anyone have any idea how to approach this?

import xlrd

filename = "data.xls"
book = xlrd.open_workbook(filenmae, formatting_info = True)

Solution

  • import xlrd
    
    filename = 'data.xls'
    book = xlrd.open_workbook(filename, formatting_info=True)
    sheet = book.sheet_by_index(0)
    max_row = sheet.nrows
    max_col = sheet.ncols
    count = 0
    for row in range(max_row):
        for col in range(max_col):
            cell = sheet.cell(row, col)
            frmt = book.xf_list[cell.xf_index]
            font = book.font_list[frmt.font_index]
            count = count+1 if font.colour_index == 10 else count
    
    print(count)
    

    You may need to play around with the colour index to find the correct one for your red. I just grabbed a cell that I knew was red and checked the colour index. More info can be found here