Python按某一列的值拆分Excel工作表
用pandas groupby把一张总表按某列(如部门、城市、业务员)的值拆成多个工作表或多个独立文件,自动命名、表头统一,告别手工筛选复制。
场景痛点
一份全公司销售明细表,要按"部门"列拆成给每个部门负责人的分表;或者按"城市"列分发到各区域。手工筛选、复制、新建表、命名,几十个部门要点几十遍。用Python按列值循环拆分,一次跑完。
用到的库
pip install pandas openpyxl
完整代码
import os
import pandas as pd
def split_by_column_to_files(input_file, column, output_dir, sheet_name=0):
"""
按某一列的值,把数据拆成多个独立Excel文件
input_file: 源文件
column: 用来拆分的列名,例如 "部门"
output_dir: 输出目录
"""
os.makedirs(output_dir, exist_ok=True)
df = pd.read_excel(input_file, sheet_name=sheet_name)
if column not in df.columns:
print(f"列[{column}]不存在,现有列: {list(df.columns)}")
return
# 按列值分组
for value, group in df.groupby(column):
# 清洗文件名,去掉非法字符
safe_name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_")
out_path = os.path.join(output_dir, f"{safe_name}.xlsx")
group.to_excel(out_path, index=False)
print(f"[{value}] -> {len(group)}行 -> {out_path}")
def split_by_column_to_sheets(input_file, column, output_file, sheet_name=0):
"""按列值拆分到同一个工作簿的不同工作表"""
df = pd.read_excel(input_file, sheet_name=sheet_name)
with pd.ExcelWriter(output_file, engine="openpyxl") as writer:
for value, group in df.groupby(column):
# 工作表名最长31字符,且不能含特殊字符
sheet_name_safe = str(value)[:31]
group.to_excel(writer, sheet_name=sheet_name_safe, index=False)
print(f"工作表[{sheet_name_safe}]写入{len(group)}行")
if __name__ == "__main__":
# 拆成多个文件
split_by_column_to_files("./销售明细.xlsx", "部门", "./部门分表")
# 拆成同一个文件的多个工作表
split_by_column_to_sheets("./销售明细.xlsx", "城市", "./城市分表.xlsx")
代码讲解
df.groupby(column)按指定列分组,迭代时value是该列的每个取值,group是对应子表。- 文件名/工作表名用
replace清理\ / :等非法字符,工作表名再用[:31]截断到Excel允许的31字符上限。 - 多工作表写法用
pd.ExcelWriter上下文管理器,一次打开写多个sheet,避免重复开关文件。
运行结果
按文件拆分时,每个部门/城市一个 .xlsx;按工作表拆分时一个文件里每个值一个sheet。控制台打印每个分组的行数。
注意事项
- 列值里如果有空值,pandas会自动丢弃该组,需要先
df[column].fillna("未填写")补上。 - 工作表名重名时后写的会覆盖先写的,建议拆分前
df[column].unique()检查一遍。 - 中文列名直接传中文字符串即可,pandas 3 对 Unicode 列名支持良好。

更新时间:2026-09-15 09:02:08