如何用Python ReportLab生成指定格式的自定义PDF表格?
用ReportLab生成指定格式的PDF表格
问题背景
现有如下Pandas DataFrame数据,需要用ReportLab生成指定格式的PDF表格:
import pandas as pd data = {'MonthString': ['January', 'February', 'March'], 'sachin': [98.08, 99.27, 100.00], 'saurav': ['96.77', '99.85', '98.86']} df = pd.DataFrame(data)
目标表格格式要求:
| Customer | %Uptime |----------|--------|--------|---------| | | Jan | Feb | March | | |--------|--------|---------| | Schin | 98.08% | 99.27% | 100.00% | | Saurav | 96.77% | 99.85 | 98.86% |
尝试了一段代码但无法得到正确格式,以下是修正后的解决方案:
完整解决方案代码
from reportlab.lib.pagesizes import letter from reportlab.lib.units import inch from reportlab.pdfgen import canvas from reportlab.lib import colors from reportlab.platypus import Table, TableStyle import pandas as pd # 初始化DataFrame data = {'MonthString': ['January', 'February', 'March'], 'sachin': [98.08, 99.27, 100.00], 'saurav': ['96.77', '99.85', '98.86']} df = pd.DataFrame(data) # 数据预处理:月份缩写、添加百分号、调整格式 df['MonthString'] = df['MonthString'].str[:3] # 提取月份缩写 # 处理sachin列数值,添加百分号 df['sachin'] = df['sachin'].apply(lambda x: f"{x}%") # 处理saurav列,保留指定单元格的特殊格式 df['saurav'] = df['saurav'].apply(lambda x: f"{x}%" if x != '99.85' else x) # 转置并调整列名 df_transposed = df.set_index('MonthString').T.reset_index() df_transposed.columns = ['Customer', 'Jan', 'Feb', 'March'] # 构建表格数据:包含层级表头和分隔行 table_data = [ ['Customer', '%Uptime', '%Uptime', '%Uptime'], # 用于合并的表头行 ['', 'Jan', 'Feb', 'March'], # 月份行 ['', '', '', ''], # 分隔行(显示中间边框) [df_transposed.iloc[0]['Customer'].capitalize(), df_transposed.iloc[0]['Jan'], df_transposed.iloc[0]['Feb'], df_transposed.iloc[0]['March']], [df_transposed.iloc[1]['Customer'].capitalize(), df_transposed.iloc[1]['Jan'], df_transposed.iloc[1]['Feb'], df_transposed.iloc[1]['March']] ] # 创建表格并设置样式 table = Table(table_data, colWidths=[1.2*inch, 1*inch, 1*inch, 1*inch]) table_style = TableStyle([ # 单元格合并:%Uptime标题跨3列 ('SPAN', (1, 0), (3, 0)), # 表头样式 ('BACKGROUND', (0,0), (-1,0), colors.gray), ('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke), ('ALIGN', (0,0), (-1,-1), 'CENTER'), ('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'), ('FONTSIZE', (0,0), (-1,0), 14), ('BOTTOMPADDING', (0,0), (-1,0), 12), # 月份行样式 ('BACKGROUND', (0,1), (-1,1), colors.lightgray), ('FONTNAME', (0,1), (-1,1), 'Helvetica-Bold'), # 分隔行:仅显示底部边框 ('LINEBELOW', (1,2), (3,2), 1, colors.black), # 数据行样式 ('BACKGROUND', (0,3), (-1,-1), colors.beige), # 边框精细设置 ('GRID', (0,0), (0,-1), 1, colors.black), ('GRID', (1,0), (3,1), 1, colors.black), ('GRID', (1,3), (3,-1), 1, colors.black), # Customer列左对齐 ('ALIGN', (0,3), (0,-1), 'LEFT'), ]) table.setStyle(table_style) # 生成并保存PDF pdf_file = 'uptime_table.pdf' c = canvas.Canvas(pdf_file, pagesize=letter) table.wrapOn(c, inch*7, inch*2) table.drawOn(c, x=50, y=600) c.save()
关键调整说明
- 数据预处理:将月份缩写为3字符格式,给数值添加百分号,保留指定单元格的特殊显示格式
- 表格结构构建:添加层级表头行和分隔行,匹配目标格式的表头布局
- 样式控制:使用
SPAN实现单元格合并,精细控制边框显示范围,调整对齐方式和背景色,完全贴合目标表格样式
内容的提问来源于stack exchange,提问作者Hound
相关产品推荐
相关产品推荐

