You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python在Excel中高亮满足偏差条件的分组单元格?

使用openpyxl实现Excel分组单元格高亮

前提准备

先安装所需依赖:

pip install openpyxl

方案1:直接用openpyxl处理原始数据(无需依赖Pandas)

适用于未提前计算差值,直接从原始Excel分组计算并上色的场景。假设你的数据结构为:

  • A列:分组标识(同一组的标识相同)
  • B列:需要比较的数值
  • 每组最后一行的B列值为该组的最终基准值

代码示例:

from openpyxl import load_workbook
from openpyxl.styles import PatternFill

# 加载目标Excel文件,确保文件处于关闭状态
wb = load_workbook("your_source_file.xlsx")
ws = wb.active  # 若指定工作表,改为 ws = wb["SheetName"]

# 定义高亮填充样式
green_fill = PatternFill(start_color="90EE90", end_color="90EE90", fill_type="solid")  # 淡绿
red_fill = PatternFill(start_color="FFCCCB", end_color="FFCCCB", fill_type="solid")    # 淡红

# 第一步:收集所有分组的行数据与基准值
groups = {}
current_group = None
current_rows = []

# 从第二行开始遍历(假设第一行是表头)
for row_idx, row in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
    group_name = row[0]
    value = row[1]
    # 获取当前数值对应的单元格对象,用于后续修改样式
    cell = ws.cell(row=row_idx, column=2)
    
    if group_name != current_group:
        # 处理上一个分组(如果存在)
        if current_group is not None:
            final_value = current_rows[-1][0]
            groups[current_group] = {"rows": current_rows, "final_val": final_value}
        # 切换到新分组
        current_group = group_name
        current_rows = [(value, cell)]
    else:
        current_rows.append((value, cell))

# 处理最后一个分组
if current_group is not None:
    final_value = current_rows[-1][0]
    groups[current_group] = {"rows": current_rows, "final_val": final_value}

# 第二步:遍历分组,根据差值设置单元格颜色
for group_data in groups.values():
    final_val = group_data["final_val"]
    if final_val == 0:  # 避免除以0报错
        continue
    # 遍历组内除基准行外的所有行
    for current_val, cell in group_data["rows"][:-1]:
        diff_percent = ((current_val - final_val) / final_val) * 100
        if diff_percent > 3:
            cell.fill = green_fill
        elif diff_percent < -3:
            cell.fill = red_fill

# 保存修改后的文件
wb.save("highlighted_result.xlsx")

方案2:结合已有的Pandas计算结果上色

如果你已经用Pandas算出了差值百分比(比如存在C列),可以直接读取计算后的文件,根据差值列快速上色:

from openpyxl import load_workbook
from openpyxl.styles import PatternFill

wb = load_workbook("your_calculated_file.xlsx")
ws = wb.active

green_fill = PatternFill(start_color="90EE90", end_color="90EE90", fill_type="solid")
red_fill = PatternFill(start_color="FFCCCB", end_color="FFCCCB", fill_type="solid")

# 假设B列是需要高亮的数值列,C列是已计算好的差值百分比
for row in range(2, ws.max_row + 1):
    diff_percent = ws.cell(row=row, column=3).value
    if diff_percent is None:
        continue
    target_cell = ws.cell(row=row, column=2)
    if diff_percent > 3:
        target_cell.fill = green_fill
    elif diff_percent < -3:
        target_cell.fill = red_fill

wb.save("highlighted_result.xlsx")

注意事项

  • 运行代码前必须关闭目标Excel文件,否则会触发权限错误
  • 若你的分组逻辑不同(比如按列分组、分组标识在其他列),只需调整代码中对应的列索引即可
  • 颜色代码可自行替换,比如使用RGB十六进制值定制高亮色

内容的提问来源于stack exchange,提问作者markacz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 15:45:54