如何使用OpenPyXL格式化带有标题的列 [英] How to format columns with headers using OpenPyXL

查看:326
本文介绍了如何使用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?

我在openpyxl网站上注意到了一些应该执行此操作的代码,但是似乎没有用.在下面:

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.

我尝试使用以下代码格式化单元格:

I tried the following code to format the cells:

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

其工作方式与上面的ws ['E7']语句相同,但格式应允许我对其执行循环.但是当我执行以下命令时:

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

它返回错误:无法排序的类型:tuple()< int()

It returns the error: unorderable types: 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

我希望第5列和第7列具有日期格式.这确实可以解决问题,但是如果我的行数超过100,则必须提高该数字.

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.

这篇关于如何使用OpenPyXL格式化带有标题的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆