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

Python实现工作表合并主要通过 pandas 和 openpyxl 或 xlsxwriter 等库来完成。最常见的情况是将多个Excel文件或多个Sheet页合并成一个工作表,便于统一分析。以下是几种典型场景的实现方法。
如果你有多个Excel文件(如 data1.xlsx、data2.xlsx),每个文件中有一个表格,想把它们按行合并到一个总表中:
import pandas as pd
import glob
<h1>获取所有Excel文件路径</h1><p>file_paths = glob.glob("*.xlsx")</p><h1>读取每个文件的数据并合并</h1><p>all_data = pd.DataFrame()
for file in file_paths:
df = pd.read_excel(file)
all_data = pd.concat([all_data, df], ignore_index=True)</p><h1>保存合并结果</h1><p>all_data.to_excel("合并结果.xlsx", index=False)</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p>如果一个Excel文件中有多个Sheet(例如“销售1月”、“销售2月”),希望把它们合并成一个DataFrame:
import pandas as pd
<h1>读取整个Excel文件的所有Sheet</h1><p>excel_file = pd.ExcelFile("多个Sheet的文件.xlsx")
all_sheets = []</p><h1>遍历每个Sheet</h1><p>for sheet_name in excel_file.sheet_names:
df = pd.read_excel(excel_file, sheet_name=sheet_name)
all_sheets.append(df)</p><h1>合并所有Sheet</h1><p>combined_df = pd.concat(all_sheets, ignore_index=True)</p><h1>保存结果</h1><p>combined_df.to_excel("合并后的Sheet.xlsx", index=False)</p>在合并时,有时需要知道每行数据来自哪个文件或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)
<p>all_data.to_excel("带来源的合并结果.xlsx", index=False)</p>基本上就这些。根据实际需求选择读取方式和合并逻辑,pandas 的 concat 是核心工具,灵活使用即可应对大多数合并场景。
以上就是python如何实现工作表合并?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号