Open In App

How to Merge all excel files in a folder using Python?

In this article, we will see how to combine all Excel files present in a folder into a single file.

Module used:

The python libraries used are:



Excel files used:

Three Excel files will be used which will be combined into a single Excel file in a folder using python. The three Excel files are x1.xlsx, x2.xlsx, and x3.xlsx:



Stepwise Approach:




# importing pandas libraries and 
# glob module
import pandas as pd
import glob




# path of the folder
path = r'test'




# reading all the excel files
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)




# Initializing empty data frame
finalexcelsheet = pd.DataFrame()




# to iterate excel file one by one 
# inside the folder
for file in filenames:
  
    # combining multiple excel worksheets 
    # into single data frames
    df = pd.concat(pd.read_excel(file, sheet_name=None),
                   ignore_index=True, sort=False)
      
    # Appending excel files one by one
    finalexcelsheet = finalexcelsheet.append(
      df, ignore_index=True)




# to print the combined data
print('Final Sheet:')
display(finalexcelsheet)




# save combined data
finalexcelsheet.to_excel(r'Final.xlsx',index=False)

Below is the complete python program based on the above approach:




#import modules
import pandas as pd
import glob
  
# path of the folder
path = r'test'
  
# reading all the excel files
filenames = glob.glob(path + "\*.xlsx")
print('File names:', filenames)
  
# initializing empty data frame
finalexcelsheet = pd.DataFrame()
  
# to iterate excel file one by one 
# inside the folder
for file in filenames:
  
    # combining multiple excel worksheets
    # into single data frames
    df = pd.concat(pd.read_excel(
      file, sheet_name=None), ignore_index=True, sort=False)
  
    # appending excel files one by one
    finalexcelsheet = finalexcelsheet.append(
      df, ignore_index=True)
  
# to print the combined data
print('Final Sheet:')
display(finalexcelsheet)
  
finalexcelsheet.to_excel(r'Final.xlsx', index=False)

Output:

Final Excel:


Article Tags :