UnicornKKYY
UnicornKKYY

Reputation: 75

Openpyxl fill the cells with color through for loop

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

Upvotes: 0

Views: 131

Answers (2)

mamo
mamo

Reputation: 265

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')

Upvotes: 1

Talha Tayyab
Talha Tayyab

Reputation: 27725

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

Upvotes: 1

Related Questions