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

如何用Pandas为SQL Server导入的表格添加跨列居中总计行

Pandas实现带合并总计行的表格处理

假设你已经通过pandas.read_sql从SQL Server读取了数据,得到包含Customer Code、Customer Name、Total Sales、Total Revenue列的DataFrame。以下是实现需求的具体步骤:

1. 模拟/读取数据

先给出模拟数据示例(实际场景替换为你的SQL读取代码即可):

import pandas as pd

# 模拟从SQL Server读取的客户销售数据
data = {
    'Customer Code': ['C001', 'C002', 'C003'],
    'Customer Name': ['Alice', 'Bob', 'Charlie'],
    'Total Sales': [1000, 2500, 1800],
    'Total Revenue': [800, 2000, 1440]
}
df = pd.DataFrame(data)

2. 添加总计行

计算数值列的总和,构建总计行并追加到DataFrame末尾:

# 计算Total Sales和Total Revenue的总和
total_sales_sum = df['Total Sales'].sum()
total_revenue_sum = df['Total Revenue'].sum()

# 创建总计行的Series,前两列填充'Total'
total_row = pd.Series({
    'Customer Code': 'Total',
    'Customer Name': 'Total',
    'Total Sales': total_sales_sum,
    'Total Revenue': total_revenue_sum
})

# 将总计行添加到DataFrame
df_with_total = df.append(total_row, ignore_index=True)

3. 设置样式实现跨列居中

利用Pandas的Styler工具,通过CSS样式实现最后一行前两列的合并居中效果:

def format_total_row(styler):
    # 让最后一行第一列跨两列显示并居中
    styler.set_table_styles([
        {
            'selector': 'tr:last-child td:first-child',
            'props': [
                ('text-align', 'center'),
                ('colspan', '2')
            ]
        },
        # 隐藏最后一行的第二列,避免重复显示'Total'
        {
            'selector': 'tr:last-child td:nth-child(2)',
            'props': [('display', 'none')]
        }
    ])
    return styler

# 应用样式并展示表格
styled_table = df_with_total.style.pipe(format_total_row)
display(styled_table)

补充说明

  • 如果需要导出为HTML,直接使用styled_table.to_html('output.html')即可保留样式;
  • 若要导出到Excel并保留合并单元格效果,需使用xlsxwriter引擎,通过其API单独处理最后一行的单元格合并操作。

内容的提问来源于stack exchange,提问作者Harrison Levesque

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 05:55:15