升级Openpyxl至2.5.3后条件格式代码触发TypeError问题求助
Root Cause
Between Openpyxl 2.4.1 and 2.5.3, the conditional formatting API got a critical refactor: the conditional_formatting.add() method changed its expected input type for the cell range parameter.
In 2.4.1, you could pass a raw string (like 'A3:B10') and the library would automatically parse it into the necessary range object. But starting in 2.5.x, the method explicitly requires a CellRange or MultiCellRange instance as the first argument. Passing a string directly now triggers the TypeError you're seeing, because the library no longer handles implicit string-to-range-object conversion.
Fix Steps
You need to explicitly create a valid range object from your string expression and pass that to the add() method instead of the raw string. Here's how to implement this:
Import the required range class from openpyxl's worksheet module:
from openpyxl.worksheet.cell_range import CellRange(Use
MultiCellRangeinstead if you're working with multiple non-contiguous ranges.)Replace your string range with a
CellRangeinstance in theadd()call. You can construct the range object first for clarity, or inline it directly:
Fixed Code Example
# Import necessary classes first from openpyxl.worksheet.cell_range import CellRange from openpyxl.formatting.rule import CellIsRule # ... rest of your script ... # Build the target cell range as a CellRange object target_range = CellRange(f'A3:B{report_query.oli_num_of_rows + 2}') # Pass the range object to the conditional formatting add method ws.conditional_formatting.add( target_range, CellIsRule( operator='equal', formula=[f'{two_days_old}'], stopIfTrue=True, fill=yellow_fill ) )
Minor Cleanup Note
Your original code had an extra trailing comma in the format() call (format(report_query.oli_num_of_rows + 2,)). While this doesn't break functionality, removing it makes the code cleaner:
# Original (with redundant comma) 'A3:B{0}'.format(report_query.oli_num_of_rows + 2,) # Cleaned up 'A3:B{0}'.format(report_query.oli_num_of_rows + 2) # Or use f-string for better readability (Python 3.6+) f'A3:B{report_query.oli_num_of_rows + 2}'
内容的提问来源于stack exchange,提问作者Emac

