在 Python 上使用 Openpyxl 时出现 PatternFill 问题。谁能帮助我吗?
我正在尝试使用 Openpyxl 中的 IF 和 Patternfill 根据单元格的文本更改单元格的背景颜色,但收到类型错误。请参阅下面的代码:
#Level - Replied Travel Alerts(RTA)
incident_index = item.body.index("incident") + 12
category_indexpos = item.body[incident_index:].index("Category") + incident_index
level = item.body[incident_index:category_indexpos]
ws.cell(row=index+2, column = 2).value = level
if "Advisory" in level:
advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")
ws.cell(row=index+2, column = 2).fill = advisory_pattern
elif "Notice" in level:
notice_pattern = Pattern(patternType = "solid", fgColor = "00B050")
ws.cell(row=index+2, column = 2).fill = notice_pattern
elif "Special" in level:
special_pattern = Pattern(patternType = "solid", fgColor= "FF0000")
ws.cell(row=index+2, column = 2).fill = special_pattern
但我在“advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")”行上收到错误。查看消息:
发生异常:TypeError 无法创建“re.Pattern”实例
有人可以帮助我吗?
谢谢
I'm trying to change the background color of a cell according to its text using IF and Patternfill from Openpyxl but I'm receiving a type error. See bellow the code:
#Level - Replied Travel Alerts(RTA)
incident_index = item.body.index("incident") + 12
category_indexpos = item.body[incident_index:].index("Category") + incident_index
level = item.body[incident_index:category_indexpos]
ws.cell(row=index+2, column = 2).value = level
if "Advisory" in level:
advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")
ws.cell(row=index+2, column = 2).fill = advisory_pattern
elif "Notice" in level:
notice_pattern = Pattern(patternType = "solid", fgColor = "00B050")
ws.cell(row=index+2, column = 2).fill = notice_pattern
elif "Special" in level:
special_pattern = Pattern(patternType = "solid", fgColor= "FF0000")
ws.cell(row=index+2, column = 2).fill = special_pattern
but I'm getting an error on the "advisory_pattern = Pattern(patternType = "solid", fgColor="FFFF00")" line. See the message:
Exception has occurred: TypeError
cannot create 're.Pattern' instances
Can anyone help me?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,re.Pattern 来自 python re 库,它与在 Openpyxl 中创建背景填充无关
首先,我会在代码顶部使用此导入:
然后您可以修改您的行以适应这种格式(我使用您的第一个填充作为我的示例):
如果您仍想将填充存储在变量中,只需确保您使用的是 openpyxl fills 库中的填充对象,而不是 python re 库中的 Pattern 对象。
Well, re.Pattern is from the python re library, which has nothing to do with creating background fills in Openpyxl
First, I would use this import at the top of your code:
Then you can modify your lines to fit this format (I used your first fill as my example):
If you want to store your fills in variables still, just make sure you are using fill objects from the openpyxl fills library and not Pattern objects from the python re library.