python将几个excel文件合并_python写完了怎么运行

python将几个excel文件合并_python写完了怎么运行合并多个 Excel 文件到一个新的 Excel 文件 可以使用 Python 的 pandas 库 它提供了读取和写入 Excel 文件的便捷方法 以下是一个使用 pandas 合并多个 Excel 文件的示例代码 pythonimport osimport pandas as pd 定义存放多个 Excel 文件的文件夹路径 file folder path to excel files

合并多个Excel文件到一个新的Excel文件,可以使用Python的`pandas`库,它提供了读取和写入Excel文件的便捷方法。以下是一个使用`pandas`合并多个Excel文件的示例代码:

python

import os

import pandas as pd

定义存放多个Excel文件的文件夹路径

file_folder = '/path/to/excel/files'

获取文件夹内所有Excel文件的列表

file_list = os.listdir(file_folder)

过滤出扩展名为.xlsx的文件

excel_files = [file for file in file_list if file.endswith('.xlsx')]

初始化一个空的DataFrame用于存储合并后的数据

combined_df = pd.DataFrame()

遍历所有Excel文件,读取数据并合并到combined_df中

for file in excel_files:

file_path = os.path.join(file_folder, file)

读取当前Excel文件的所有sheet

xls = pd.ExcelFile(file_path)

for sheet_name in xls.sheet_names:

读取每个sheet的数据

sheet_df = pd.read_excel(xls, sheet_name=sheet_name)

将读取的数据追加到combined_df中

combined_df = combined_df.append(sheet_df, ignore_index=True)

将合并后的数据保存到一个新的Excel文件

output_file = '/path/to/output/combined_excel.xlsx'

combined_df.to_excel(output_file, index=False)

请确保将`/path/to/excel/files`替换为包含多个Excel文件的文件夹路径,以及将`/path/to/output/combined_excel.xlsx`替换为你希望保存合并后Excel文件的路径。

编程小号
上一篇 2026-03-16 20:08
下一篇 2026-03-16 20:04

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/72777.html