XlsxWriter条件格式能否传入多类型值对?遇TypeError报错咨询
Hey, let's break down what's happening here. When you tried passing a list like ["no_blanks", "blanks"] to the type parameter in worksheet.conditional_format(), you got a TypeError: unhashable type: 'list'—and that's because XlsxWriter doesn't support passing multiple types in a single conditional_format call.
Why the error occurs
The type key in the format dictionary expects a single string value (like "blanks" or "no_blanks"), not a list. Under the hood, XlsxWriter tries to process this value in a way that requires hashable types, and since lists are unhashable, it throws that error. The API is designed to handle one conditional rule per conditional_format call.
The correct approach: separate calls for each condition
If you want to apply the same format abc to both blank and non-blank cells in the same range, you just need to call conditional_format twice—once for each type:
# Apply format to non-blank cells worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "no_blanks", "format": abc}) # Apply format to blank cells worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "blanks", "format": abc})
This creates two separate conditional formatting rules targeting the same cell range, which achieves exactly what you were trying to do with the list approach.
Bonus: Using formulas for complex multi-condition rules
If you ever need more advanced logic (like "apply format if either condition X or Y is true"), you can use the "formula" type instead. For example, to target all cells (blank or not):
worksheet.conditional_format(first_row, first_col, last_row, last_col, {"type": "formula", "criteria": 'OR(ISBLANK(A1), NOT(ISBLANK(A1)))', "format": abc})
But for your specific use case, the two separate conditional_format calls are simpler and more readable.
内容的提问来源于stack exchange,提问作者abhilash mishra

