pandas 生成excel多级表头

使用pandas导出excel 表格时类似这种

其中含有多级表头的情况也就是涉及到表头需要合并单元格(横向及纵向)

1、表头设置

python 复制代码
columns = [("xx公司路产月报表","序号","序号"),("xx公司路产月报表","单位","单位"),("xx公司路产月报表","本月使用","份数"),("xx公司路产月报表","本月使用","金额"),("xx公司路产月报表","本月作废","份数"),("xx公司路产月报表","本年累计","使用份数"),("xx公司路产月报表","本年累计","金额"),("xx公司路产月报表","本年累计","作废份数"),("xx公司路产月报表","月末结存","份数")]
df = pd.DataFrame(dep_data_list)
df.columns = pd.MultiIndex.from_tuples(columns)
df.to_excel(excelfile)

结果时这样的

产生的结果会多一列索引,多一行空白行,及纵向的单元格没有被合并

python 复制代码
# 列索引不显示
df.to_excel(excelfile,index=False)
# 不被允许,报错NotImplementedError("Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.",

2、隐藏多余的行

python 复制代码
with pd.ExcelWriter(excelfile,engine='xlsxwriter') as writer:
     df.to_excel(writer,sheet_name='报表数据统计')
     writer.sheets['报表数据统计'].set_column(0,0,None,None,{"hidden":True})
     writer.sheets['报表数据统计'].set_row(3,None,None,{"hidden":True})
     writer.save()

结果展示

3、表头纵向合并居中展示、表头字体放大

python 复制代码
workbook = load_workbook(excelfile)
sheet = workbook.active
name = workbook.get_sheet_names

sheet.merge_cells('B2:B3')
sheet.merge_cells('C2:C3')
cell = sheet['B1']
font = Font(size=20,bold=True)
cell.font = font
sheet['B2'].alignment = Alignment(horizontal="center", vertical="center")
sheet['C2'].alignment = Alignment(horizontal="center", vertical="center")
workbook.save(excelfile)

结果展示

相关推荐
智航GIS1 分钟前
ArcGIS Python零基础脚本开发教程---1.1 Describe 函数
开发语言·python·arcgis
Dreaming_of_you5 分钟前
pytorch/cv2/pil/torchvision处理图像缩小的最佳方案
人工智能·pytorch·python·opencv
Testopia37 分钟前
走一遍 AI 学习之路 —— AI实例系列说明
开发语言·人工智能·python
机 _ 长39 分钟前
YOLO26 改进 | 训练策略 | 知识蒸馏 (Response + Feature + Relation)
python·深度学习·yolo·目标检测·机器学习·计算机视觉
草青工作室43 分钟前
java-FreeMarker3.4自定义异常处理
java·前端·python
hrrrrb1 小时前
【算法设计与分析】随机化算法
人工智能·python·算法
D___H1 小时前
Part10_编写自己的解释器
python
Zero_to_zero12341 小时前
Claude code系列(一):claude安装、入门及基础操作指令
人工智能·python
Yeats_Liao1 小时前
异步推理架构:CPU-NPU流水线设计与并发效率提升
python·深度学习·神经网络·架构·开源