1

I want to set color red to a series of cells(one column to other) in an excel sheet and using openpyxl.

I was able to find how to give cells a certain color from the official documentation but I was unable to figure out how to give a range.

Basically, I want something like this using openpyxl:

inheritance_cell_format = wb.add_format()
inheritance_cell_format.set_font_color('red')
ws.conditional_format( 0, skip_cols-2, ws.max_row, skip_cols-1, { 'type': 'cell', 'criteria': '=', 'value': '⇒', 'format': inheritance_cell_format } )

The above snippet works in xlsxwriter.

As of now, obviously, I am getting an error on the first line stating that workbook doesn't have an attribute 'add_format()'

Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81

1 Answers1

1

You can color a range with a loop using the method .iter_rows() or iter_cols(). You could import PatternFill to color it.

import openpyxl as px
from openpyxl.styles import PatternFill

wb = px.load_workbook(file) #imports file
ws = wb.active #Active sheet (first one)
for row in sheet.iter_rows(min_row=1, max_col=3, max_row=2): #max row and col (range)
   for cell in row:
       cell.fill = PatternFill(start_color="FF0000", fill_type = "solid") #html colors


wb.save(file)