t_openxyl.py 1.5 KB

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