答案:Python通过pandas库实现工作表合并,常用concat方法。首先读取多个Excel文件或Sheet页数据,依次添加到DataFrame中,可选择性加入来源标识列,最后统一保存为新Excel文件,适用于多文件或多Sheet的行向合并场景。

Python实现工作表合并主要通过 pandas 和 openpyxl 或 xlsxwriter 等库来完成。最常见的情况是将多个Excel文件或多个Sheet页合并成一个工作表,便于统一分析。以下是几种典型场景的实现方法。
合并多个Excel文件中的数据
如果你有多个Excel文件(如 data1.xlsx、data2.xlsx),每个文件中有一个表格,想把它们按行合并到一个总表中:
import pandas as pdimport glob获取所有Excel文件路径
file_paths = glob.glob("*.xlsx")
读取每个文件的数据并合并
all_data = pd.DataFrame()for file in file_paths:df = pd.read_excel(file)all_data = pd.concat([all_data, df], ignore_index=True)
保存合并结果
all_data.to_excel("合并结果.xlsx", index=False)
立即学习“Python免费学习笔记(深入)”;
合并同一个Excel中多个Sheet页
如果一个Excel文件中有多个Sheet(例如“销售1月”、“销售2月”),希望把它们合并成一个DataFrame:
import pandas as pd读取整个Excel文件的所有Sheet
excel_file = pd.ExcelFile("多个Sheet的文件.xlsx")all_sheets = []
遍历每个Sheet
for sheet_name in excel_file.sheet_names:df = pd.read_excel(excel_file, sheet_name=sheet_name)all_sheets.append(df)
合并所有Sheet
combined_df = pd.concat(all_sheets, ignore_index=True)
保存结果
combined_df.to_excel("合并后的Sheet.xlsx", index=False)
添加来源标识区分数据来源
在合并时,有时需要知道每行数据来自哪个文件或Sheet,可以添加一列标记:
all_data = pd.DataFrame()for file in glob.glob("*.xlsx"): df = pd.read_excel(file) df["来源文件"] = file # 添加来源列 all_data = pd.concat([all_data, df], ignore_index=True)all_data.to_excel("带来源的合并结果.xlsx", index=False)
基本上就这些。根据实际需求选择读取方式和合并逻辑,pandas 的 concat 是核心工具,灵活使用即可应对大多数合并场景。
以上就是python如何实现工作表合并?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1381974.html
微信扫一扫
支付宝扫一扫