Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - วิธีรวมไฟล์ Excel ทั้งหมดในโฟลเดอร์


เพื่อรวมไฟล์ Excel ทั้งหมดในโฟลเดอร์ ใช้โมดูล Glob และเมธอด append()

สมมติไฟล์ Excel ของเราอยู่บน Desktop:

Sales1.xlsx

Python - วิธีรวมไฟล์ Excel ทั้งหมดในโฟลเดอร์

Sales2.xlsx

Python - วิธีรวมไฟล์ Excel ทั้งหมดในโฟลเดอร์

หมายเหตุ – อาจต้องติดตั้งแพ็กเกจ openpyxl และ xlrd

ก่อนอื่น กำหนดพาธที่เก็บไฟล์ Excel ที่ต้องการรวม ดึงไฟล์และอ่านด้วย glob:

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

สร้าง DataFrame ว่างสำหรับไฟล์ Excel เอาต์พุตที่รวมแล้ว:

outputxlsx = pd.DataFrame()

กระบวนการจริง: วนลูปอ่านไฟล์ Excel concat และ append ข้อมูล:

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 ที่รวมแล้วจะถูกสร้างที่ตำแหน่งเดิม:

Python - วิธีรวมไฟล์ Excel ทั้งหมดในโฟลเดอร์