How to format columns with headers using OpenPyXL

2019-07-21 00:43发布

问题:

I am trying to format certain columns in a date format.

I am able to successfully change an individual cell's format using:

date_style = Style(number_format="M/D/YYYY")
ws['E7'].style = date_style

but is there an easier way to apply a blanket formatting to a column aside from the header?

I noticed some code on the openpyxl website that is supposed to do this, but it didn't seem to work. It is below:

col = ws.column_dimensions['E']
col.number_format = "M/D/YYYY"

and I assume if it did work correctly, it would apply to the header as well.

EDIT: I tried the following code to format the cells:

ws.cell(row=1,column=5).style=date_style

Which works the same as the ws['E7'] statement above but is in a format that should allow me to run a loop on it. But when I execute the following:

for i in ws.rows[1:]:
    ws.cell(row=i,column=5).style = date_style

It returns the error: unorderable types: tuple() < int()

回答1:

I figured it out, although probably not the most elegant way:

date_style = Style(number_format="M/D/YYYY")
for col in range(5,8,2):
    for row in range(2,100,1):
        ws.cell(row=row,column=col).style = date_style

I wanted columns 5 and 7 to have the date formatting. This did the trick, but of course if I have more than 100 rows, I'll have to raise that number.