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

如何为DataFrame指定表头设置颜色并导出保存为Excel文件

问题描述

假设我有如下所示的DataFrame:

col1    sub col 2     col3       col4
0    A        A_1          pass        2
1    A        A_2          pass        4
2    A        A_1          fail        4
3    A        A_1          fail        5
4    A        A_1          pass        3
5    A        A_2          fail        2

我需要将表头“sub col 2”的填充色设置为黄色,再将该DataFrame导出保存为Excel文件,打开最终输出的Excel文件时对应表头为黄色填充效果。

解决方法

可以使用pandas搭配openpyxl引擎实现该需求,完整代码如下:

import pandas as pd
from openpyxl.styles import PatternFill

# 构造示例DataFrame,可替换为你自己的DataFrame
data = {
    "col1": ["A", "A", "A", "A", "A", "A"],
    "sub col 2": ["A_1", "A_2", "A_1", "A_1", "A_1", "A_2"],
    "col3": ["pass", "pass", "fail", "fail", "pass", "fail"],
    "col4": [2, 4, 4, 5, 3, 2]
}
df = pd.DataFrame(data)

# 导出Excel并设置表头样式
output_file = "result.xlsx"
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
    # 写入DataFrame,不保留索引列
    df.to_excel(writer, index=False, sheet_name="Sheet1")
    # 获取当前工作表对象
    worksheet = writer.sheets["Sheet1"]
    # 定义黄色实心填充样式
    yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
    # 遍历表头行(Excel中第一行索引为1),匹配目标列名后设置填充
    for cell in worksheet[1]:
        if cell.value == "sub col 2":
            cell.fill = yellow_fill

运行代码后生成的result.xlsx文件打开后,即可看到sub col 2表头已为黄色填充效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 19:15:02