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)

结果展示

相关推荐
akhfuiigabv9 分钟前
使用Neo4j-Cypher-FT实现自然语言查询图数据库
数据库·python·oracle·neo4j
繁依Fanyi27 分钟前
828华为云征文|华为Flexus云服务器搭建OnlyOffice私有化在线办公套件
服务器·开发语言·前端·python·算法·华为·华为云
zhangfeng113329 分钟前
在 PyTorch 中,除了 pad_sequence 还有哪些其他处理序列数据的函数?时间序列数据 预处理
人工智能·pytorch·python·深度学习
~在杰难逃~33 分钟前
关于订单信息的Excel数据分析报告
笔记·数据分析·excel·数据分析报告
python15643 分钟前
Python Numpy布尔数组在数据分析中的应用
python·数据分析·numpy
AIAdvocate1 小时前
力扣-96.不同的二叉搜索树 题目详解
python·算法·动态规划
luthane1 小时前
python 实现entropy熵算法
python·算法·概率论
akhfuiigabv1 小时前
探索Timescale Vector与Postgres数据库的融合:AI应用的新选择
数据库·人工智能·python
hakesashou1 小时前
ruby和python哪个好学
开发语言·python·ruby
NiNg_1_2341 小时前
Python协程详解
开发语言·python