Convert and Combine Multiple Excel Files into One CSV with pandas
To combine Excel files into one CSV in Python, read their sheets with pandas read_excel(), append the rows with concat(), and save with to_csv(). The same script can also produce a CSV for each workbook. Use it when the sheets have the same fields under the same column names.
Prepare the input files and sheets
From a terminal, install pandas and openpyxl, which reads .xlsx files, in the Python environment you will use. Make an excel_in folder in your working directory and put the source .xlsx files there. The script skips subfolders and temporary Excel lock files beginning with ~$.
python -m pip install pandas openpyxl
Combine Excel workbooks and sheets into one CSV
Save the code below as merge_excel.py and run it from the working directory. Put column names in the first row. The example expects item_id, item_name, and quantity. Change COLUMNS to fit your headers. The script writes the columns in that order even if the sheet columns are ordered differently.
Set SHEETS = None for all sheets, 0 for the first sheet, or a name such as "Jan" for one named sheet per workbook. For a single workbook, put just that file in the folder. Set WRITE_PER_WORKBOOK = True if you also want separate CSVs in output/by_workbook.
from pathlib import Path
import pandas as pd
INPUT = Path("excel_in")
OUTPUT = Path("output")
COLUMNS = ["item_id", "item_name", "quantity"]
SHEETS = None # None: all; 0: first; "Jan": by name
WRITE_PER_WORKBOOK = False
paths = sorted(
path for path in INPUT.glob("*.xlsx")
if path.is_file() and not path.name.startswith("~$")
)
if not paths:
raise FileNotFoundError(f"No .xlsx files in {INPUT.resolve()}")
workbooks = {}
for path in paths:
data = pd.read_excel(
path,
sheet_name=SHEETS,
engine="openpyxl",
dtype="string",
keep_default_na=False,
)
sheets = data if isinstance(data, dict) else {SHEETS: data}
parts = []
for name, frame in sheets.items():
if set(frame.columns) != set(COLUMNS):
raise ValueError(f"{path.name}, sheet {name}: {list(frame.columns)}")
parts.append(frame[COLUMNS])
workbooks[path.stem] = pd.concat(parts, ignore_index=True)
merged = pd.concat(workbooks.values(), ignore_index=True)
if merged.empty:
raise ValueError("No data rows in the selected sheets")
OUTPUT.mkdir(exist_ok=True)
merged.to_csv(OUTPUT / "combined.csv", index=False, encoding="utf-8-sig", mode="x")
if WRITE_PER_WORKBOOK:
folder = OUTPUT / "by_workbook"
folder.mkdir(exist_ok=True)
for stem, frame in workbooks.items():
frame.to_csv(folder / f"{stem}.csv", index=False, encoding="utf-8-sig", mode="x")
print(f"{len(paths)} workbooks, {len(merged)} rows")
python merge_excel.py
Check the result and preserve leading zeros
For the result below, put the rows for 00123 and 00124 in the first sheet of 01.xlsx and the row for 00125 in 02.xlsx. Set the ID cells to Text before entering the values. The script reads workbooks in filename order and follows each workbook’s sheet and row order. Check that the printed row count matches the total data rows in the selected sheets.
item_id,item_name,quantity
00123,Café,2
00124,NA,3
00125,"Tea, green",1
dtype="string" reads values as strings, and keep_default_na=False keeps markers such as NA as ordinary text. If Excel stores 123 as a number and displays it with a 00000 format, the stored value still lacks the leading zeros. CSV has no cell formatting or data types. If reopening it in Excel, import the ID column as text. utf-8-sig adds a byte order mark that helps Excel detect UTF-8, and index=False omits the pandas row index.
Combine existing CSV files
If the data is already in CSV files, save the code below as merge_csv.py. Use the per-workbook CSVs from the previous step or your existing comma-separated UTF-8 files, and adjust INPUT if needed. To combine only two files, put only those two in the input folder. Keep the merged output outside that folder so the next run cannot read it back as an input.
from pathlib import Path
import pandas as pd
INPUT = Path("output/by_workbook")
OUTPUT = Path("output/combined_from_csv.csv")
COLUMNS = ["item_id", "item_name", "quantity"]
files = sorted(path for path in INPUT.glob("*.csv") if path.is_file())
if not files:
raise FileNotFoundError(f"No CSV files in {INPUT.resolve()}")
parts = []
for path in files:
frame = pd.read_csv(path, dtype="string", keep_default_na=False, encoding="utf-8-sig")
if set(frame.columns) != set(COLUMNS):
raise ValueError(f"{path.name}: {list(frame.columns)}")
parts.append(frame[COLUMNS])
merged = pd.concat(parts, ignore_index=True)
if merged.empty:
raise ValueError("No data rows in the selected CSV files")
OUTPUT.parent.mkdir(exist_ok=True)
merged.to_csv(OUTPUT, index=False, encoding="utf-8-sig", mode="x")
print(f"{len(files)} CSV files, {len(merged)} rows")
python merge_csv.py
Troubleshoot files and column mismatches
- If the column check fails, open the workbook and sheet named in the error. Check headers, trailing spaces, title rows above the table, and information-only sheets. Align the headers in a copy or select the appropriate sheet.
- The same ID can occur more than once.
concat()stacks rows. To join fields by ID or remove duplicates, first decide how to handle repeated IDs. Compare the expected data row counts before merging. - Both scripts use
mode="x"to prevent overwrites. To rerun, move existing results to a different location or change the output path. The script holds the inputs in memory, so try a small batch first for large datasets.




