Working with multiple Excel files can quickly become tedious when you're tasked with consolidating them into one file. Fortunately, Python offers a fast and efficient way to automate this process.
In this tutorial, we'll learn how to merge several Excel files—each containing a single worksheet—into a single workbook, with each file becoming a separate sheet.
Use Case
Imagine you receive monthly sales reports from multiple branches. Each branch sends its own Excel file. You want to merge them all into one workbook where:
- Each branch’s data is a separate sheet.
- The sheet names are based on the original filenames.
Requirements
We'll use the following Python libraries:
openpyxl: For reading and writing Excel files (XLSX format).
pandas: For reading Excel data easily.
glob: For finding Excel files in a directory.
os: To extract filenames for sheet names.
Step 1: Install Python
First, ensure Python is installed on your system.
For Windows/macOS/Linux:
Download Python from the official website:
https://www.python.org/downloads/
Then verify the installation:
Step 2: Install Required Dependencies
We will use the xlwings library to manipulate Excel files while maintaining full formatting.
Open your terminal or command prompt and run:
Tip: You can also create a virtual environment for better project management.
Step 3: Prepare Your Excel File
Here’s a full script to export each worksheet as a separate Excel file:
By automating Excel merging with Python, you can save hours of manual copy-pasting. This is perfect for financial reports, department overviews, or aggregating form responses.