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)

结果展示

相关推荐
烛阴4 小时前
简单入门Python装饰器
前端·python
好开心啊没烦恼4 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开4 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
2301_805054566 小时前
Python训练营打卡Day59(2025.7.3)
开发语言·python
万千思绪6 小时前
【PyCharm 2025.1.2配置debug】
ide·python·pycharm
微风粼粼7 小时前
程序员在线接单
java·jvm·后端·python·eclipse·tomcat·dubbo
云天徽上8 小时前
【PaddleOCR】OCR表格识别数据集介绍,包含PubTabNet、好未来表格识别、WTW中文场景表格等数据,持续更新中......
python·ocr·文字识别·表格识别·paddleocr·pp-ocrv5
你怎么知道我是队长8 小时前
python-input内置函数
开发语言·python
叹一曲当时只道是寻常8 小时前
Python实现优雅的目录结构打印工具
python
hbwhmama9 小时前
python高级变量XIII
python