Python - 如何合并文件夹中的所有 Excel 文件
要合并文件夹中的所有 Excel 文件,请使用 Glob 模块和 append() 方法。
假设桌面上的 Excel 文件如下 −
Sales1.xlsx

Sales2.xlsx

注意 − 您可能需要安装 openpyxl 和 xlrd 软件包。
首先,设置要合并的所有 Excel 文件所在的路径。获取 Excel 文件并使用 glob 读取它们 −
path = "C:\Users\amit_\Desktop\"
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)接下来,创建一个空的 DataFrame,用于合并的输出 Excel 文件,它将从上述两个 Excel 文件中获取数据 −
outputxlsx = pd.DataFrame()
现在,可以看到实际过程,即首先使用 for 循环迭代 Excel 文件。读取 Excel 文件,将它们连接起来并追加数据 −
for file in filenames: df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True, sort=False) outputxlsx = outputxlsx.append(df, ignore_index=True)
示例
以下是代码 −
import pandas as pd
import glob
# getting excel files to be merged from the Desktop
path = "C:\Users\amit_\Desktop\"
# read all the files with extension .xlsx i.e. excel
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)
# empty data frame for the new output excel file with the merged excel files
outputxlsx = pd.DataFrame()
# for loop to iterate all excel files
for file in filenames:
# using concat for excel files
# after reading them with read_excel()
df = pd.concat(pd.read_excel( file, sheet_name=None), ignore_index=True, sort=False)
# appending data of excel files
outputxlsx = outputxlsx.append( df, ignore_index=True)
print('Final Excel sheet now generated at the same location:')
outputxlsx.to_excel("C:/Users/amit_/Desktop/Output.xlsx", index=False)输出
这将生成以下输出,即合并的 Excel 文件将生成在相同的位置 −

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP