Python实现一键合并N个Excel工作表/文件
数据散落在不同Excel,手动整合耗时又易错!
在日常工作中,你是不是经常遇到这样的场景?
每个月,销售部门会给你发一份Excel报表,每个月的文件名都不同。你需要把过去12个月的数据合并到一张总表里。
公司不同业务线的数据分散在几十个Excel文件或不同的工作表里,但它们之间又有关联(比如都包含“客户ID”)。你需要把它们联接起来,进行全面分析。
手动打开、复制、粘贴……这个过程不仅耗时耗力,还极易出错,一个Ctrl+C/V的失误,就可能导致整个报表前功尽弃!

我们将手把手教你如何利用数据处理的andas库,轻松实现:
秒速合并: 将多个Excel工作表或文件按行堆叠,瞬间整合海量数据。
精准联接: 像拼图一样,根据共同的列,精确匹配和联接不同表格的数据。
最终,你将拥有一个强大的 Excel万能数据整合器,让你的数据处理和数据分析 工作效率翻倍!
1.Pandas核心:表格数据处理的瑞士军刀入门
要实现高效的Python合并Excel和Excel多表整合,我们离不开Python数据处理的明星库——Pandas。它以其强大的DataFrame结构,成为处理表格数据的行业标准,堪称数据处理领域的“瑞士军刀”!
安装Pandas:
pip install pandas openpyxl # openpyxl用于Pandas读写xlsx文件
1.1 安装与核心组件:DataFrame,你的数据“容器”
在深入合并之前,我们先了解Pandas最核心的概念:
DataFrame: 你可以把它想象成一个加强版的Excel表格。它有行和列,每一列都有名字,每一行也有索引。但它比Excel更强大、更灵活,更适合用代码进行高效操作。
Series: DataFrame中的一列,可以看作一个带索引的列表。
1.2 读取Excel数据:Pandas让数据“活”起来
场景: 你需要将Excel表格中的数据,导入到Python程序中进行处理。
作用: Pandas可以非常方便地读取Excel文件,将其内容转换为DataFrame对象,让数据在Python中“活”起来,为数据自动化处理奠定基础。
代码:
import pandas as pd
import os
def read_excel_to_dataframe(file_path):
"""
使用Pandas读取Excel文件,转换为DataFrame。
这是Python数据分析入门和Excel自动化处理的基础。
:param file_path: Excel文件路径
:return: 读取到的DataFrame对象
"""
if not os.path.exists(file_path): return print(f"❌ Excel文件不存在:{file_path}")
try:
df = pd.read_excel(file_path) # 核心代码:一行命令读取Excel
print(f"✅ 成功读取Excel文件:'{os.path.basename(file_path)}'")
print(" --- DataFrame头部数据(前5行):---")
print(df.head()) # 打印DataFrame的前5行
print("\n --- DataFrame信息概览:---")
print(df.info()) # 打印DataFrame的概要信息(列名、非空值数量、数据类型)
return df
except Exception as e:
print(f"❌ 读取Excel失败:{e}")
return None
if __name__ == "__main__":
# 准备一个测试Excel文件,例如 'products.xlsx'
# 内容可以简单一点,如:
# ProductID | ProductName | Category
# 001 | Laptop | Electronics
# 002 | Mouse | Accessories
test_excel_path = os.path.expanduser("~/Desktop/products.xlsx")
os.makedirs(os.path.dirname(test_excel_path), exist_ok=True)
# 确保有测试Excel文件存在
if not os.path.exists(test_excel_path):
# 简单创建测试文件(实际用户需手动创建)
pd.DataFrame({'ProductID': ['001', '002'],
'ProductName': ['Laptop', 'Mouse'],
'Category': ['Electronics', 'Accessories']}).to_excel(test_excel_path, index=False)
print(f"临时测试文件 '{os.path.basename(test_excel_path)}' 已创建。")
df_products = read_excel_to_dataframe(test_excel_path)
if df_products is not None:
print("\nDataFrame读取成功,你可以开始你的数据自动化处理了!")
步骤:
准备Excel文件: 在桌面创建一个名为products.xlsx的Excel文件,输入一些简单的数据(如产品ID、名称、类别)。
修改代码路径: 复制上方代码到VS Code,保存为pandas_excel_read.py。修改 test_excel_path。
运行: 在VS Code终端运行 python pandas_excel_read.py。
效果:

1.3 基础数据查看:快速预览,心中有数
一旦数据加载到DataFrame,Pandas提供了多种方法让你快速预览数据结构和内容。
- df.head():查看前N行(默认5行)。
- df.tail():查看后N行。
- df.info():查看列名、非空值数量、数据类型、内存占用等。
- df.describe():对数值列进行统计描述(均值、标准差等)。
- df.columns:查看所有列名。
这是你进行任何数据自动化处理前,快速了解数据的“体检报告”!
表格:Pandas DataFrame常用查看方法
| 方法 | 作用 | 示例代码 |
|---|---|---|
| df.head() | 查看前5行数据 | df.head() |
| df.info() | 查看数据框概要信息(列名、类型、非空计数) | df.info() |
| df.describe() | 数值列统计描述(均值、最大值等) | df.describe() |
| df.shape | 获取数据框的行数和列数 | df.shape |
| 图注:Pandas DataFrame常用查看方法一览,快速了解你的数据! |
2.秒速合并:pd.concat合并多个工作表/文件
场景: 你每月都会收到一份销售数据Excel,或者一个Excel文件里分了Q1、Q2、Q3、Q4四个工作表。现在你需要把这些数据全部堆叠到一张大表里,进行年终总计。手动复制粘贴?太慢了!
方案: pd.concat()函数是Pandas中实现Python合并Excel、进行数据自动化处理的利器,它能将多个结构相似的DataFrame按行(或列)“堆叠”起来,实现Excel多表整合的秒速合并!
作用: pd.concat()像胶水一样,将多个DataFrame简单地拼接在一起。
2.1 按行堆叠:多个结构相同表格的简单合并
代码:
import pandas as pd
import os
def merge_excel_rows_concat(file_paths, output_file_path):
"""
使用pd.concat按行合并多个Excel文件或工作表。
这是Python合并Excel的基础,适合结构相同的表格堆叠。
:param file_paths: 包含要合并的Excel文件路径列表
:param output_file_path: 合并后Excel文件的输出路径
"""
all_dfs = []
print("🚀 正在读取并准备合并文件...")
for f_path in file_paths:
if os.path.exists(f_path):
df = pd.read_excel(f_path)
all_dfs.append(df)
print(f" ✅ 已读取:{os.path.basename(f_path)}")
else:
print(f"❌ 文件不存在,跳过:{os.path.basename(f_path)}")
if not all_dfs:
print("ℹ️ 没有找到任何文件可供合并。")
return
# **核心操作:pd.concat按行合并DataFrame**
# axis=0 表示按行合并(默认值),ignore_index=True 重新生成索引
merged_df = pd.concat(all_dfs, ignore_index=True)
os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
merged_df.to_excel(output_file_path, index=False) # 保存合并后的DataFrame到Excel
print(f"✨ 成功合并 {len(all_dfs)} 个文件到:'{os.path.basename(output_file_path)}'")
print(" --- 合并后数据头部 ---")
print(merged_df.head())
print(f" 总行数:{len(merged_df)}")
if __name__ == "__main__":
# 准备测试数据:创建两个或更多结构相同的Excel文件
# 例如:
# sales_q1.xlsx (Product, Sales)
# sales_q2.xlsx (Product, Sales)
q1_path = os.path.expanduser("~/Desktop/sales_q1.xlsx")
q2_path = os.path.expanduser("~/Desktop/sales_q2.xlsx")
output_merged_path = os.path.expanduser("~/Desktop/annual_sales_report.xlsx")
# 简单创建测试文件
pd.DataFrame({'Product': ['Laptop', 'Mouse'], 'Sales': [100, 150]}).to_excel(q1_path, index=False)
pd.DataFrame({'Product': ['Monitor', 'Keyboard'], 'Sales': [200, 120]}).to_excel(q2_path, index=False)
file_list = [q1_path, q2_path]
merge_excel_rows_concat(file_list, output_merged_path)
步骤:
准备Excel文件: 在桌面创建sales_q1.xlsx和sales_q2.xlsx,确保它们的列结构相同。
修改代码路径: 修改 file_list 和 output_merged_path。
运行: 运行 python merge_concat.py。
展示:

2.2 批量合并:一键整合文件夹下所有Excel文件
如果一个文件夹里有几十个Excel文件,逐个指定路径就太麻烦了!Python合并Excel的威力在于批量处理。
场景: 你需要将某个文件夹(如“每月销售数据”)下所有Excel文件(如202301.xlsx, 202302.xlsx…)全部合并到一个总表。
方案: 结合os模块遍历文件夹,pd.read_excel()读取,pd.concat()合并,轻松实现Excel多表整合的自动化。
代码:
import pandas as pd
import os
def merge_all_excels_in_folder(folder_path, output_file_name="merged_all_data.xlsx"):
"""
一键合并指定文件夹下所有Excel文件。
这是高效的Python合并Excel和数据自动化处理脚本。
:param folder_path: 包含Excel文件的文件夹路径
:param output_file_name: 合并后Excel文件的名称
"""
if not os.path.exists(folder_path): return print(f"❌ 文件夹不存在:{folder_path}")
all_files = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith(('.xls', '.xlsx'))]
if not all_files: return print(f"ℹ️ 文件夹 '{folder_path}' 中没有找到Excel文件。")
all_dfs = []
print(f"🚀 正在合并文件夹 '{folder_path}' 下的所有Excel文件...")
for f_path in all_files:
try:
df = pd.read_excel(f_path)
all_dfs.append(df)
print(f" ✅ 已读取:{os.path.basename(f_path)}")
except Exception as e:
print(f"❌ 读取文件 '{os.path.basename(f_path)}' 失败:{e}。跳过。")
if not all_dfs: return print("ℹ️ 没有成功读取任何Excel文件。")
merged_df = pd.concat(all_dfs, ignore_index=True)
output_path = os.path.join(os.path.dirname(folder_path), output_file_name)
os.makedirs(os.path.dirname(output_path), exist_ok=True)
merged_df.to_excel(output_path, index=False)
print(f"✨ 成功合并所有Excel文件到:'{os.path.basename(output_path)}'")
print(f" 总行数:{len(merged_df)}")
if __name__ == "__main__":
# 准备测试数据:在桌面创建 'MonthlySales' 文件夹,并在其中放入多个Excel文件
# 例如:
# MonthlySales/Jan_2023.xlsx (Product, Sales)
# MonthlySales/Feb_2023.xlsx (Product, Sales)
input_folder = os.path.expanduser("~/Desktop/MonthlySales")
os.makedirs(input_folder, exist_ok=True)
# 示例创建文件
# pd.DataFrame({'Product': ['A'], 'Sales': [10]}).to_excel(os.path.join(input_folder, 'Jan_2023.xlsx'), index=False)
# pd.DataFrame({'Product': ['B'], 'Sales': [20]}).to_excel(os.path.join(input_folder, 'Feb_2023.xlsx'), index=False)
merge_all_excels_in_folder(input_folder, "YearlySalesSummary.xlsx")
步骤:
准备Excel文件: 在桌面创建一个名为MonthlySales的文件夹,放入多个列结构相同的Excel文件。
修改代码路径: 修改 input_folder。
运行: 运行 python merge_all_excels.py。
效果展示:

3.精准联接:pd.merge实现多表联立查询与数据匹配
pd.concat()适用于简单堆叠,但当你的数据分散在不同Excel文件,且这些文件之间存在某种“关联”(如客户ID、订单号),你需要将它们“拼图”一样组合起来,这时就需要pd.merge(),它能实现Excel多表整合中的精准联接,是Python数据分析入门的必备技能!
作用: pd.merge()类似于SQL数据库中的JOIN操作,根据一个或多个共同的列,将两个DataFrame的数据进行匹配和组合。
3.1 核心讲解:像拼图一样匹配数据
场景: 你有一个“客户信息表”(客户ID、姓名、地址),另一个是“客户订单表”(客户ID、订单号、商品)。你希望将这两张表通过“客户ID”关联起来,生成一份包含客户姓名和其对应订单的完整列表。
方案: pd.merge()的内连接(inner join)模式,只会保留两个表中共同存在的匹配项。
代码:
import pandas as pd
import os
def inner_merge_example(customers_path, orders_path, output_path):
"""
使用pd.merge进行内连接,根据共同列匹配数据。
这是Python合并Excel,实现精准数据匹配的核心。
:param customers_path: 客户信息Excel文件路径
:param orders_path: 客户订单Excel文件路径
:param output_path: 合并后输出Excel文件路径
"""
if not (os.path.exists(customers_path) and os.path.exists(orders_path)):
print(f"❌ 缺少一个或多个源文件。")
return
try:
df_customers = pd.read_excel(customers_path)
df_orders = pd.read_excel(orders_path)
print("🚀 正在执行内连接:")
print(" --- 客户信息表 ---")
print(df_customers.head())
print("\n --- 客户订单表 ---")
print(df_orders.head())
# **核心操作:pd.merge 内连接**
# on='CustomerID' 表示根据 CustomerID 列进行匹配
merged_df = pd.merge(df_customers, df_orders, on='CustomerID', how='inner')
os.makedirs(os.path.dirname(output_path), exist_ok=True)
merged_df.to_excel(output_path, index=False)
print(f"\n✨ 内连接成功!结果保存到:'{os.path.basename(output_path)}'")
print(" --- 合并后数据头部 ---")
print(merged_df.head())
print(f" 总行数:{len(merged_df)}")
except Exception as e:
print(f"❌ 内连接失败:{e}")
if __name__ == "__main__":
# 准备测试数据
customers_file = os.path.expanduser("~/Desktop/customers.xlsx")
orders_file = os.path.expanduser("~/Desktop/orders.xlsx")
output_merged_file = os.path.expanduser("~/Desktop/customer_orders_inner.xlsx")
# 简单创建测试文件
pd.DataFrame({'CustomerID': [1, 2, 3],
'Name': ['Alice', 'Bob', 'Charlie'],
'City': ['NY', 'LA', 'SF']}).to_excel(customers_file, index=False)
pd.DataFrame({'OrderID': ['A001', 'A002', 'A003'],
'CustomerID': [1, 2, 4], # 注意:CustomerID 4 不在客户表中
'Amount': [100, 150, 200]}).to_excel(orders_file, index=False)
inner_merge_example(customers_file, orders_file, output_merged_file)
步骤:
准备Excel文件: 在桌面创建customers.xlsx和orders.xlsx,确保有共同列CustomerID。
修改代码路径: 修改 customers_file, orders_file, output_merged_file。
运行: 运行 python merge_inner.py。
效果:

3.2 深度应用:左右连接,数据匹配更灵活
除了内连接,pd.merge()还支持外连接(outer join)、左连接(left join)和右连接(right join),让你在数据自动化处理中,无论数据缺失与否,都能灵活组合!
左连接 (Left Join): 以左边表(df_customers)为基准,保留左表所有行,并尝试匹配右表数据。如果右表没有匹配项,则显示NaN(Not a Number)。
右连接 (Right Join): 与左连接相反,以右边表(df_orders)为基准。
外连接 (Outer Join): 包含所有表中所有的行,无论它们是否匹配。
代码:
import pandas as pd
import os
def flexible_merge_example(customers_path, orders_path, output_prefix="merged_data"):
"""
使用pd.merge进行左连接、右连接和外连接,实现更灵活的数据匹配。
:param customers_path: 客户信息Excel文件路径
:param orders_path: 客户订单Excel文件路径
:param output_prefix: 输出文件名前缀
"""
if not (os.path.exists(customers_path) and os.path.exists(orders_path)):
print(f"❌ 缺少一个或多个源文件。")
return
try:
df_customers = pd.read_excel(customers_path)
df_orders = pd.read_excel(orders_path)
# 左连接 (Left Join)
left_merged_df = pd.merge(df_customers, df_orders, on='CustomerID', how='left')
left_output_path = os.path.expanduser(f"~/Desktop/{output_prefix}_left.xlsx")
left_merged_df.to_excel(left_output_path, index=False)
print(f"\n✨ 左连接成功!结果保存到:'{os.path.basename(left_output_path)}'")
print(left_merged_df.head())
# 右连接 (Right Join)
right_merged_df = pd.merge(df_customers, df_orders, on='CustomerID', how='right')
right_output_path = os.path.expanduser(f"~/Desktop/{output_prefix}_right.xlsx")
right_merged_df.to_excel(right_output_path, index=False)
print(f"\n✨ 右连接成功!结果保存到:'{os.path.basename(right_output_path)}'")
print(right_merged_df.head())
# 外连接 (Outer Join)
outer_merged_df = pd.merge(df_customers, df_orders, on='CustomerID', how='outer')
outer_output_path = os.path.expanduser(f"~/Desktop/{output_prefix}_outer.xlsx")
outer_merged_df.to_excel(outer_output_path, index=False)
print(f"\n✨ 外连接成功!结果保存到:'{os.path.basename(outer_output_path)}'")
print(outer_merged_df.head())
except Exception as e:
print(f"❌ 灵活连接失败:{e}")
if __name__ == "__main__":
customers_file = os.path.expanduser("~/Desktop/customers.xlsx")
orders_file = os.path.expanduser("~/Desktop/orders.xlsx")
# 确保测试文件存在,且包含非匹配的 CustomerID 以便演示 Left/Right/Outer Join
# (与3.1节创建的文件类似,但需要确保有非匹配项)
flexible_merge_example(customers_file, orders_file, "customer_orders")
步骤:
准备Excel文件: 使用与3.1节相同或类似的数据,但确保CustomerID有不匹配的情况,以演示NaN值。
修改代码路径: 修改 customers_file, orders_file。
运行: 运行 python merge_flexible.py。
展示:

4.阶段性总结:你的“Excel万能数据整合器”!
恭喜你!通过本篇文章,你已经掌握了Python合并Excel的精髓,亲手打造了一个能够秒合并N个Excel工作表/文件的**“Excel万能数据整合器”**!
我们深入学习了Pandas库,它堪称表格数据处理的瑞士军刀,实现了:
数据读取: 轻松将Excel数据导入Python DataFrame。
秒速合并 (pd.concat): 无论是几个Excel文件,还是一个文件夹下所有的Excel文件,都能一键按行堆叠,实现Excel多表整合。
精准联接 (pd.merge): 像数据库查询一样,根据共同的列,实现精确的数据匹配(内连接、左连接、右连接),解决数据散落在不同Excel的痛点。
5.后话:数据大融合,开启智能数据分析新篇章!
通过本篇文章,你已经掌握了Python合并Excel的强大能力,为你的办公自动化之旅又增添了一个重量级技能!你学会了如何利用Pandas这个Python实用工具,高效地进行Excel的数据合并与联接
到此这篇关于Python实现一键合并N个Excel工作表/文件的文章就介绍到这了,更多相关Python合并Excel内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python用selenium打开浏览器后秒关闭浏览器的解决办法
最近朋友在学Selenium的时候遇到一个问题,当执行完selenium程序后,浏览器会闪退也就是自动关闭,这篇文章主要给大家介绍了关于python用selenium打开浏览器后秒关闭浏览器的解决办法,需要的朋友可以参考下2023-07-07


最新评论