Home > database >  Openpyxl fill the cells with color through for loop
Openpyxl fill the cells with color through for loop

Time:01-19

How can I fill up the cells by using for loop instead of repeating the code several times?

My code:

ws['A1'].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')
ws['B2'].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')
ws['C3'].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')
ws['D4'].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')

my expected result is: enter image description here

CodePudding user response:

for x,y in enumerate(['A','B','C','D'],1):
    ws[f"{y}{x}"].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')

# here y will go from A to D and x will start from 1 as declared in enumerate

This is how it will go:

for x,y in enumerate(['A','B','C','D'],1):
  print(f"{y}{x}")
A1
B2
C3
D4

CodePudding user response:

You can use chr(64 i) to get the characters. 65 corresponds to A, 66 to B and so on.

Here you can find an ASCII table wih the associations number - character

for i in range(1, 5):
    ws[f"{chr(64   i)}{i}"].fill = PatternFill(start_color = 'FFFF00',fill_type='solid')
  • Related