Gộp nhiều file Excel trong cùng một thư mục thành một file duy nhất. Sử dụng module glob để tìm file và pd.concat() / append() để gộp dữ liệu.
Chuẩn bị
- Cài đặt:
pip install openpyxl xlrd(để đọc .xlsx, .xls). - Các file Excel đặt trong cùng thư mục (ví dụ: Desktop).
Mã nguồn
import pandas as pd
import glob
# Đường dẫn thư mục chứa file Excel
path = "C:\\Users\\YourName\\Desktop\\"
# Lấy danh sách file .xlsx
filenames = glob.glob(path + "\\*.xlsx")
print('Tên file:', filenames)
# DataFrame rỗng để chứa dữ liệu gộp
outputxlsx = pd.DataFrame()
# Duyệt từng file, đọc và gộp
for file in filenames:
# Đọc tất cả sheet, gộp thành 1 DataFrame
df = pd.concat(pd.read_excel(file, sheet_name=None), ignore_index=True, sort=False)
# Thêm vào DataFrame kết quả
outputxlsx = outputxlsx.append(df, ignore_index=True)
# Lưu file gộp
outputxlsx.to_excel("C:/Users/YourName/Desktop/Output.xlsx", index=False)
print('File gộp đã tạo tại:', "C:/Users/YourName/Desktop/Output.xlsx")
Giải thích
glob.glob(path + "\\*.xlsx")trả về list đường dẫn file .xlsx.pd.read_excel(file, sheet_name=None)đọc tất cả sheet, trả về dict {sheet_name: DataFrame}.pd.concat(..., ignore_index=True)gộp các sheet của một file, reset index.outputxlsx.append(df, ignore_index=True)nối dọc (row-wise) dữ liệu các file.to_excel(..., index=False)lưu ra file, không ghi index.
Lưu ý hiệu năng
Với nhiều file/ dữ liệu lớn, nên dùng list comprehension rồi pd.concat một lần:
dfs = [pd.concat(pd.read_excel(f, sheet_name=None), ignore_index=True) for f in filenames]
outputxlsx = pd.concat(dfs, ignore_index=True)
Nhanh hơn việc append lặp lại trong vòng lặp (deprecated từ pandas 1.4).