You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python生成格式美观的成品报告?解决HTML与Excel方案问题

解决方案

一、HTML报告:解决f-string大括号冲突并美化

1. 大括号转义方法

在f-string中,要保留样式里的{},只需写成{{}}即可避免被识别为占位符。以下是完整实现示例:

import pandas as pd

# 示例DataFrame
df = pd.DataFrame({
    '姓名': ['张三', '李四', '王五'],
    '年龄': [25, 30, 28],
    '部门': ['研发', '销售', '运营']
})

# HTML模板,用{{}}转义样式中的大括号
html_template = f"""
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>业务数据报告</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 30px; }}
        .report-header {{ text-align: center; margin-bottom: 40px; }}
        .table-section {{ margin-bottom: 50px; }}
        .table-title {{ font-size: 18px; font-weight: bold; margin-bottom: 10px; }}
        .table-desc {{ color: #555; font-size: 14px; margin-bottom: 15px; }}
        table {{
            border-collapse: collapse;
            width: 100%;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }}
        th {{
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 12px;
            text-align: left;
            font-weight: 600;
        }}
        td {{
            border: 1px solid #dee2e6;
            padding: 10px;
        }}
        tr:nth-child(even) {{ background-color: #f8f9fa; }}
    </style>
</head>
<body>
    <div class="report-header">
        <h1>月度业务报告</h1>
        <p>生成时间:2024-05-20</p>
    </div>
    
    <!-- 带DataFrame的报告模块 -->
    <div class="table-section">
        <div class="table-title">员工基本信息表</div>
        <div class="table-desc">以下为公司各部门在职员工的基础信息统计,包含姓名、年龄及所属部门</div>
        {df.to_html(index=False)}
    </div>

    <!-- 可重复添加其他4份报告模块 -->
</body>
</html>
"""

# 保存HTML文件
with open('beautiful_report.html', 'w', encoding='utf-8') as f:
    f.write(html_template)

2. 批量生成多份报告

如果要生成4份带DataFrame的报告,只需循环创建多个table-section模块,替换对应的标题、描述和DataFrame即可。

二、Excel报告生成方案

用pandas配合XlsxWriter引擎,可生成带格式的多工作表Excel报告,完美适配你的需求:

import pandas as pd

# 准备5份报告数据:1份纯文本,4份DataFrame
text_content = [
    "月度业务概览",
    "1. 本月新增员工:8人",
    "2. 本月总营收:35万元",
    "3. 核心产品占比:65%",
    "4. 部门协作效率提升:12%"
]
df_list = [
    pd.DataFrame({'姓名': ['张三', '李四'], '年龄': [25, 30], '部门': ['研发', '销售']}),
    pd.DataFrame({'产品': ['A', 'B'], '销量': [120, 210], '营收': [6000, 12600]}),
    pd.DataFrame({'部门': ['研发', '销售'], '人数': [20, 15], '达标率': [90, 85]}),
    pd.DataFrame({'日期': ['2024-05-01', '2024-05-15'], '访客量': [500, 620], '转化率': [3, 4]})
]
df_titles = ['员工信息表', '产品销售数据', '部门绩效统计', '流量转化报表']
df_descs = [
    '在职员工基础信息汇总',
    '本月各产品销量及营收明细',
    '各部门人员规模与绩效达标率',
    '半月度网站访客与转化数据'
]

# 创建Excel写入对象
with pd.ExcelWriter('business_report.xlsx', engine='xlsxwriter') as writer:
    workbook = writer.book
    # 定义样式
    title_format = workbook.add_format({'bold': True, 'font_size': 16, 'align': 'center'})
    desc_format = workbook.add_format({'font_size': 12, 'color': '#666'})
    header_format = workbook.add_format({'bold': True, 'bg_color': '#f2f2f2', 'border': 1})
    cell_format = workbook.add_format({'border': 1, 'valign': 'top'})

    # 写入纯文本报告
    text_sheet = workbook.add_worksheet('概览报告')
    text_sheet.merge_range('A1:D1', '月度业务概览', title_format)
    for row, line in enumerate(text_content[1:], start=2):
        text_sheet.write(f'A{row}', line, cell_format)
    text_sheet.set_column('A:D', 20)

    # 循环写入4份带DataFrame的报告
    for idx, (df, title, desc) in enumerate(zip(df_list, df_titles, df_descs), start=1):
        sheet_name = f'报告{idx}'
        df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=3)
        worksheet = writer.sheets[sheet_name]
        
        # 添加标题和描述
        worksheet.merge_range('A1:D1', title, title_format)
        worksheet.write('A2', desc, desc_format)
        
        # 应用表头样式
        for col_num, col_name in enumerate(df.columns):
            worksheet.write(3, col_num, col_name, header_format)
        
        # 应用单元格样式并调整列宽
        worksheet.set_column(0, len(df.columns)-1, 18)
        for row_num in range(4, len(df)+4):
            for col_num in range(len(df.columns)):
                worksheet.write(row_num, col_num, df.iloc[row_num-4, col_num], cell_format)

三、其他可选方案

  • PDF报告:用WeasyPrint将美化后的HTML转为PDF,适合需要打印的正式文档;或用ReportLab直接绘制PDF内容。
  • 交互式报告:用Streamlit快速搭建网页交互式报告,支持实时筛选、图表展示,适合内部数据分析场景。

内容的提问来源于stack exchange,提问作者maciej.o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:40:26