Style Normal 已经存在 - Python - OpenPyxl
Style Normal exists already - Python - OpenPyxl
我研究了许多 Whosebug 问题,但其中 none 似乎解决了我的问题。在特定条件下,我正在使用 Python 和 Openpyxl 用红色填充整行。我做了所有必要的进口:
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)))
当我要求打印第一次出现的单元格时,它给了我
<Cell 'Divers'.A4>
这正是我要找的。
但是,每次都会出现以下错误:"Style Normal exists already"。其余代码中绝对没有任何单元格格式或样式,但 Excel 文件单元格确实已经填充了黄色。
知道如何解决这个问题吗?在此先感谢您的帮助。
如果使用 NamedStyle
,您需要传递一个名称。
red_foreground = NamedStyle(
name="RedForeground",
fill=PatternFill(
patternType='solid',
fill_type='solid',
fgColor=Color(RED)
)
)
由于您要将此 NamedStyle
分配给多个单元格,因此将其注册到您的工作簿是有意义的。
wb.add_named_style(red_foreground)
然后你可以更新它对单元格的应用,像这样:
for cell in sheet[i]:
cell.style = "RedForeground"
参考:
我也遇到了这个问题,最后发现是因为有2个样式重名。这通常是您使用 copy.copy(style)
时造成的。然后更改其中一个style.name = 'newname'
后,它将起作用。
此代码将解决已经存在的命名样式。
for index,cur_style in enumerate(excel_workbook._named_styles):
if cur_style.name == 'my_new_style':
excel_workbook._named_styles[index] = my_new_style
my_new_style.bind(excel_workbook)
break
else:
excel_workbook.add_named_style(my_new_style)
但是,在您的情况下,您应该使用“Normal”以外的其他名称,因为“Normal”是默认的命名样式,只需找到另一个名称即可使用我粘贴的代码
我研究了许多 Whosebug 问题,但其中 none 似乎解决了我的问题。在特定条件下,我正在使用 Python 和 Openpyxl 用红色填充整行。我做了所有必要的进口:
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)))
当我要求打印第一次出现的单元格时,它给了我
<Cell 'Divers'.A4>
这正是我要找的。 但是,每次都会出现以下错误:"Style Normal exists already"。其余代码中绝对没有任何单元格格式或样式,但 Excel 文件单元格确实已经填充了黄色。
知道如何解决这个问题吗?在此先感谢您的帮助。
如果使用 NamedStyle
,您需要传递一个名称。
red_foreground = NamedStyle(
name="RedForeground",
fill=PatternFill(
patternType='solid',
fill_type='solid',
fgColor=Color(RED)
)
)
由于您要将此 NamedStyle
分配给多个单元格,因此将其注册到您的工作簿是有意义的。
wb.add_named_style(red_foreground)
然后你可以更新它对单元格的应用,像这样:
for cell in sheet[i]:
cell.style = "RedForeground"
参考:
我也遇到了这个问题,最后发现是因为有2个样式重名。这通常是您使用 copy.copy(style)
时造成的。然后更改其中一个style.name = 'newname'
后,它将起作用。
此代码将解决已经存在的命名样式。
for index,cur_style in enumerate(excel_workbook._named_styles):
if cur_style.name == 'my_new_style':
excel_workbook._named_styles[index] = my_new_style
my_new_style.bind(excel_workbook)
break
else:
excel_workbook.add_named_style(my_new_style)
但是,在您的情况下,您应该使用“Normal”以外的其他名称,因为“Normal”是默认的命名样式,只需找到另一个名称即可使用我粘贴的代码