Merging Excel files in Python, minimally
The whole job is: walk a folder, read each sheet, find the header, write rows under column names. Here is the smallest version that is actually correct.
The core loop
Read with openpyxl.load_workbook(path, read_only=True, data_only=True) so formulas come back as values and memory stays low. Skip names starting with ~$. Find the header row, build the name→index map, then append {name: row[i]} for every data row.
Write with a single workbook created once and saved once at the end.
Step by step
- Collect paths with
Path(folder).rglob("*.xlsx"), filtering lock files. - Per file: find the header row, build the column map.
- Accumulate dicts keyed by column name.
- Write the union of column names as the header, then every row.
The command, concretely
from pathlib import Path
from openpyxl import load_workbook, Workbook
def header_row(rows):
best, score = 0, -1
for i, row in enumerate(rows[:8]):
n = sum(1 for c in row if isinstance(c, str) and 0 < len(c.strip()) <= 24)
if n > score:
best, score = i, n
return best
records, cols = [], []
for p in Path("data").rglob("*.xlsx"):
if p.name.startswith("~$"):
continue
ws = load_workbook(p, read_only=True, data_only=True).worksheets[0]
rows = [list(r) for r in ws.iter_rows(values_only=True)]
if not rows:
continue
h = header_row(rows)
names = [str(c).strip() if c is not None else f"Column {i+1}"
for i, c in enumerate(rows[h])]
for c in names:
if c not in cols:
cols.append(c)
for r in rows[h + 1:]:
if not any(v not in (None, "") for v in r):
continue
records.append({n: (r[i] if i < len(r) else None) for i, n in enumerate(names)})
wb = Workbook(); ws = wb.active
ws.append(cols)
for rec in records:
ws.append([rec.get(c) for c in cols])
wb.save("merged.xlsx")
print(f"{len(records)} rows, {len(cols)} columns")
What goes wrong
data_only=True on an unsaved file
If the file was never calculated by Excel, formula cells come back as None. Open and save once in Excel, or accept blanks.
Appending to the output inside the loop
Saving per file is quadratic and can corrupt the file if interrupted. Write once.
Using pandas for 100 files
pd.concat is fine, but reading 100 workbooks with pandas uses far more memory than read_only=True streaming.
Questions people actually ask
Can I keep the source file name?
Add "Source file": p.name to each record — the column is worth having.
What about .xls?
xlrd handles the old format, but converting to .xlsx once is simpler.
Do it now, in this browser
Drop the folder in, check the detected header, merge. Nothing is uploaded — the file is processed in the tab. Free for one-off merges; the unlimited local build is $9.