Computer >> Máy Tính >  >> Lập trình >> Python

Python - Cách hợp nhất tất cả các tệp excel trong một thư mục

Để hợp nhất tất cả các tệp excel trong một thư mục, hãy sử dụng mô-đun Glob và phương thức append ().

Giả sử sau đây là các tệp excel của chúng tôi trên Máy tính để bàn -

Sales1.xlsx

Python - Cách hợp nhất tất cả các tệp excel trong một thư mục

Sales2.xlsx

Python - Cách hợp nhất tất cả các tệp excel trong một thư mục

Lưu ý - Bạn có thể cần cài đặt các gói openpyxl và xlrd.

Đầu tiên, hãy đặt đường dẫn chứa tất cả các tệp excel bạn muốn hợp nhất. Nhận các tệp excel và đọc chúng bằng cách sử dụng global -

path = "C:\\Users\\amit_\\Desktop\\"

filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)

Tiếp theo, tạo khung dữ liệu trống cho tệp excel đầu ra đã hợp nhất sẽ lấy dữ liệu từ hai tệp excel trên -

outputxlsx = pd.DataFrame()

Bây giờ, có thể thấy quá trình thực tế, tức là lúc đầu, lặp lại các tệp excel bằng vòng lặp for. Đọc các tệp excel, nối chúng và nối dữ liệu -

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)

Ví dụ

Sau đây là mã -

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)

Đầu ra

Điều này sẽ tạo ra kết quả sau, tức là tệp excel đã hợp nhất sẽ được tạo tại cùng một vị trí -

Python - Cách hợp nhất tất cả các tệp excel trong một thư mục