简体   繁体   English

如何使用OpenPyXL格式化带有标题的列

[英]How to format columns with headers using OpenPyXL

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. 我在openpyxl网站上注意到了一些应该执行此操作的代码,但是似乎没有用。 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. 它的工作方式与上面的ws ['E7']语句相同,但格式应允许我对其执行循环。 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() 它返回错误:不可排序的类型:tuple()<int()

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. 我希望第5列和第7列具有日期格式。 This did the trick, but of course if I have more than 100 rows, I'll have to raise that number. 这确实可以解决问题,但是如果我的行数超过100,则必须增加该数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM