Skip to content
Advertisement

python, how to fill entire row? row(i).fill = PatternFill

My code currently does this, I’m wondering if there is a shorter way to write this?

sheet.cell(row=i, column=3).fill = PatternFill(start_color='ff0000', end_color='ff0000', fill_type="solid")
sheet.cell(row=i, column=4).fill = PatternFill(start_color='ff0000', end_color='ff0000', fill_type="solid")
sheet.cell(row=i, column=5).fill = PatternFill(start_color='ff0000', end_color='ff0000', fill_type="solid")
sheet.cell(row=i, column=6).fill = PatternFill(start_color='ff0000', end_color='ff0000', fill_type="solid")

Advertisement

Answer

A simple loop maybe?

for r in range(3, 7):
   sheet.cell(row = i, column = r).fill = PatternFill(start_color= 'ff0000', end_color= 'ff0000', fill_type = "solid")

You could also move that configuration outside the loop if you’d like, that may make configuration easier:

pfKwargs = {'start_color': 'ff0000', 'end_color': 'ff0000', 'fill_type': 'solid'}

for r in range(3, 7):
   sheet.cell(row = i, column = r).fill = PatternFill(**pfKwargs)

Or perhaps move it into a function:

def addFills(sheet, start = 3, count = 4, start_color='ff0000', end_color='ff0000', fill_type="solid")
     for r in range(start, start + count):
        sheet.cell(row = i, column = r).fill = PatternFill(
                                                  start_color=start_color, 
                                                  end_color=end_color, 
                                                  fill_type=fill_type)

addFills(sheet) # does the same as the above.
addFills(sheet, 1, 200) # does the same as the above, starting at 1 and ending at 201
addFills(sheet, end_color='00ff00') # Same as above only green end color.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement