| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- from openpyxl import Workbook
- from openpyxl.styles import PatternFill
- from openpyxl.formatting.rule import CellIsRule
- from utils.logu import get_logger
- logger = get_logger('test')
- # 创建新工作簿和工作表
- wb = Workbook()
- ws = wb.active
- # 先填充示例数据(实际使用时替换为你的真实数据)
- data = [
- # B C D E F G H I J K L
- [5000, 0, 0, 8000, 0, 0, 15000, 0, 0, 20000], # 第1行
- [12000, 0, 0, 9500, 0, 0, 8000, 0, 0, 5000], # 第2行
- [9000, 0, 0, 11000, 0, 0, 13000, 0, 0, 9999] # 第3行
- ]
- for row in data:
- ws.append(row)
- # 创建红色填充样式
- red_fill = PatternFill(
- start_color="FF0000", # 红色
- end_color="FF0000",
- fill_type="solid"
- )
- # 配置参数
- threshold = 10000 # 阈值
- target_columns = ['A', 'D', 'H', 'K'] # 要设置条件格式的列
- # 获取实际数据范围的最大行数
- max_row = ws.max_row
- # 为每个目标列添加条件格式
- for col in target_columns:
- # 构造列范围(例如:B1:B3)
- cell_range = f"{col}1:{col}{max_row}"
-
- # 创建条件格式规则
- rule = CellIsRule(
- operator='greaterThan',
- formula=[threshold], # 注意参数是列表类型
- stopIfTrue=True, # 遇到符合条件的单元格后停止其他规则检查
- fill=red_fill
- )
-
- # 将规则应用到工作表
- ws.conditional_formatting.add(cell_range, rule)
- logger.info(f"应用条件格式到 {cell_range} (值 > 10000) {rule}")
- # 保存工作簿
- wb.save("conditional_formatting_example.xlsx")
|