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

如何将带多级索引列的pandas DataFrame导出为一级列不合并、二级列合并的Excel

实现方案

核心思路是使用xlsxwriter手动控制表头写入和单元格合并逻辑,避开pandas默认导出的合并规则,同时消除多余空行。

完整可运行代码

import pandas as pd
import xlsxwriter

# 构造示例DataFrame,你的实际数据可跳过这一步
data = {('Germany', 'Population', 2015): {0: 26572, 1: 12372, 2: 26480},
 ('Germany', 'Population', 2020): {0: 28985, 1: 41730, 2: 46811},
 ('Germany', 'GDP', 2015): {0: 25367, 1: 35112, 2: 37487},
 ('Germany', 'GDP', 2020): {0: 32194, 1: 37214, 2: 30372},
 ('Germany', 'GDP', 2010): {0: 44835, 1: 40748, 2: 48703},
 ('Germany', 'CO2', 2020): {0: 14415, 1: 16088, 2: 37997},
 ('Germany', 'CO2', 2030): {0: 45785, 1: 46963, 2: 43135}}
df = pd.DataFrame(data)

# 导出配置
output_file = "统计数据导出.xlsx"
workbook = xlsxwriter.Workbook(output_file)
worksheet = workbook.add_worksheet()

# 表头格式自定义,可按需修改
header_format = workbook.add_format({
    "bold": True,
    "align": "center",
    "valign": "vcenter"
})

# 提取三级列索引
l0_country = df.columns.get_level_values(0).tolist()
l1_metric = df.columns.get_level_values(1).tolist()
l2_year = df.columns.get_level_values(2).tolist()
col_total = len(df.columns)

# 写入第一级表头:每列单独显示国家名,不合并
for col in range(col_total):
    worksheet.write(0, col, l0_country[col], header_format)

# 写入第二级表头:相同指标自动合并
cur_col = 0
while cur_col < col_total:
    metric = l1_metric[cur_col]
    # 定位当前指标覆盖的连续列范围
    end_col = cur_col
    while end_col < col_total and l1_metric[end_col] == metric:
        end_col += 1
    end_col -= 1
    worksheet.merge_range(1, cur_col, 1, end_col, metric, header_format)
    cur_col = end_col + 1

# 写入第三级表头:年份每列单独显示
for col in range(col_total):
    worksheet.write(2, col, l2_year[col], header_format)

# 写入数据部分,直接接在年份表头下,无空行
for row_num, row_data in enumerate(df.values, start=3):
    for col_num, val in enumerate(row_data):
        worksheet.write(row_num, col_num, val)

# 保存文件
workbook.close()

效果说明

  • 第一级国家名列全部单独显示,无合并
  • 第二级统计指标按所属分类自动合并单元格
  • 年份表头与数据行直接衔接,无多余空行
  • 可通过修改header_format参数自定义表头样式、添加列宽调整等配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:27:03