样式正常已经存在-Python-OpenPyxl [英] Style Normal exists already - Python - OpenPyxl

查看:344
本文介绍了样式正常已经存在-Python-OpenPyxl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了很多stackoverflow问题,但是似乎没有一个问题可以解决我的问题.我使用Python和Openpyxl在给定特定条件的情况下用红色填充整行.我做了所有必要的输入:

I have looked into many stackoverflow questions but none of them seemed to solve my problem. I am using Python and Openpyxl to fill a whole row with red given a certain condition. I did all the importations necessary :

from openpyxl.styles import PatternFill, NamedStyle, Color
from openpyxl.styles.colors import RED

我的代码如下:

for cell in sheet[i]:
    cell.style = NamedStyle(fill=PatternFill(patternType='solid',
                                    fill_type='solid', 
                                    fgColor=Color(RED)))

当我要求打印单元格的第一次出现时,它给了我

When I ask to print the first occurence of cell it gives me

<Cell 'Divers'.A4> 

这就是我要寻找的. 但是,每次都会出现以下错误:样式法线已经存在".其余代码中绝对没有任何单元格格式或样式,但Excel文件单元格确实已经用黄色填充.

which is what I am looking for. However, the following error comes every time : "Style Normal exists already". There is absolutely no cell formatting or style whatsoever in the rest of the code but the Excel file cells are indeed filled with yellow already.

关于如何解决此问题的任何想法?预先感谢您的帮助.

Any idea on how to solve this ? Thanks in advance for any help.

推荐答案

如果使用NamedStyle,则需要传递名称.

If using a NamedStyle, you're required to pass a name.

red_foreground = NamedStyle(
    name="RedForeground",
    fill=PatternFill(
        patternType='solid',
        fill_type='solid', 
        fgColor=Color(RED)
    )
)

由于您要将此NamedStyle分配给多个单元格,因此有必要将其注册到您的工作簿中.

Since you're assigning this NamedStyle to more than one cell, it makes sense to register it to your workbook.

wb.add_named_style(red_foreground)

然后您可以将其应用程序更新到单元格,如下所示:

Then you can update it's application to cells, like so:

for cell in sheet[i]:
    cell.style = "RedForeground"

参考:

  • 创建NamedStyle
  • 命名样式构造函数
  • Reference:

    • Creating NamedStyle
    • NamedStyle Constructor
    • 这篇关于样式正常已经存在-Python-OpenPyxl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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