我正在嘗試使用 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”實體
誰能幫我?
謝謝
uj5u.com熱心網友回復:
嗯,re.Pattern來自python re庫,和Openpyxl中創建背景填充無關
首先,我將在代碼頂部使用此匯入:
from openpyxl.styles import fills
然后你可以修改你的行以適應這種格式(我用你的第一個填充作為我的例子):
ws.cell(row=index 2, column = 2).fill = fills.PatternFill("solid", fgColor="FFFF00")
如果您仍想將填充存盤在變數中,只需確保您使用的是 openpyxl 填充庫中的填充物件,而不是 python re 庫中的 Pattern 物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/438578.html
上一篇:當我跨列自動填充時,如何增加不同的作業表單元格參考行?
下一篇:Excel雙重條件
