Style Normal exists already - Python - OpenPyxl

為{幸葍}努か 提交于 2019-12-11 05:33:50

问题


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

And my code is the following :

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> 

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.


回答1:


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

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"

Reference:

  • Creating NamedStyle
  • NamedStyle Constructor



回答2:


I also have this problem, and finally found that it was because there were 2 styles, of which had the same name. This is usually caused when you use copy.copy(style). Then after change one of the style.name = 'newname', it will work.



来源:https://stackoverflow.com/questions/45055488/style-normal-exists-already-python-openpyxl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!