乐于分享
好东西不私藏

Pandas 批量导出多工作表PDF报表(matplotlib绘图+多Sheet合并输出)

Pandas 批量导出多工作表PDF报表(matplotlib绘图+多Sheet合并输出)
Excel报表需要转为PDF分发给业务,手动导出效率低;结合matplotlib绘图+多Sheet数据,自动化生成完整PDF运营报表,支持多图表+明细数据组合输出。
场景:按渠道拆分销售明细Sheet,分别绘制月度营收趋势图,将所有渠道图表+明细表格整合输出一份完整PDF汇报文件。核心知识点:matplotlib画布绘制、Pandas表格转画布、PDF多页保存、循环批量生成图表。

① 字段含义说明

② 生成多渠道测试数据

import pandas as pdimport numpy as npmonth_list = ["2026-01","2026-02","2026-03","2026-04","2026-05","2026-06"]channel_list = ["APP","小程序","官网"]df_list = []for chan in channel_list:    temp = pd.DataFrame({        "stat_month": month_list,        "channel": [chan]*6,        "revenue": np.random.uniform(800001800006).round(2),        "order_count": np.random.randint(30012006)    })    df_list.append(temp)df_all = pd.concat(df_list)# 分Sheet写入Excelwith pd.ExcelWriter("channel_month_sales.xlsx", engine="openpyxl"as writer:    for chan in channel_list:        sub = df_all[df_all["channel"] == chan]        sub.to_excel(writer, sheet_name=chan, index=False)print("多渠道分Sheet销售数据生成完成")

③ 核心PDF批量导出代码

import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib.backends.backend_pdf import PdfPagesplt.rcParams['font.sans-serif'] = ['Arial Unicode MS','SimHei']# 读取Excel全部工作表excel_file = pd.ExcelFile("channel_month_sales.xlsx")sheet_names = excel_file.sheet_names# 创建PDF文件,循环多页输出with PdfPages("渠道月度销售汇报.pdf"as pdf:    for sheet in sheet_names:        df = pd.read_excel("channel_month_sales.xlsx", sheet_name=sheet)        # 新建画布:上半部分图表,下半部分表格        fig, (ax1, ax2) = plt.subplots(21, figsize=(14,9), dpi=100)        # 绘制营收趋势折线图        ax1.plot(df["stat_month"], df["revenue"], marker="o", linewidth=2.5, color="#1f56bd")        ax1.set_title(f"{sheet}渠道月度营收趋势", fontsize=14)        ax1.set_ylabel("月度营收")        ax1.grid(alpha=0.3)        # 表格绘图        table = ax2.table(cellText=df.values, colLabels=df.columns, loc="center")        table.auto_set_font_size(False)        table.set_fontsize(10)        ax2.axis("off")        plt.tight_layout()        pdf.savefig(fig)        plt.close()print("多渠道图表+明细PDF报表导出完成")
查看pdf输出结果

总结

借助PdfPages实现多页PDF自动化生成,将可视化图表与原始明细表格整合输出,替代手动截图、导出Excel再转PDF的繁琐流程,适合月度、季度固定汇报文件自动化产出。