หากต้องการรวมไฟล์ 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()
ตอนนี้ กระบวนการจริงสามารถเห็นได้ เช่น ในตอนแรก ให้วนซ้ำไฟล์ excel โดยใช้ for loop อ่านไฟล์ 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 ที่ผสานจะถูกสร้างขึ้นที่ตำแหน่งเดียวกัน -
