Append Excel worksheets with Python
Combine matching first-row headers from two workbooks into one values-only XLSX.
View code and setup
Before you start
- Install Python 3. Create the environment below, save the Python example as task.py, then run .venv/bin/python task.py in the folder containing input.xlsx. On Windows, use py -m venv .venv and .venv\Scripts\python.exe in place of .venv/bin/python. Replace Inventory with your worksheet name.
python3 -m venv .venv
.venv/bin/python -m pip install openpyxlfrom openpyxl import Workbook, load_workbook
output = Workbook()
target = output.active
target.title = "Inventory"
expected_header = None
for filename in ["first.xlsx", "second.xlsx"]:
source = load_workbook(filename, read_only=True, data_only=True)
rows = source["Inventory"].iter_rows(values_only=True)
header = next(rows)
if expected_header is None:
expected_header = header
target.append(header)
elif header != expected_header:
raise ValueError(f"Headers differ in {filename}")
for row in rows:
target.append(row)
source.close()
output.save("merged.xlsx").venv/bin/python task.pyLimits and output
- These data recipes use saved cell results, not recalculated formulas. They do not copy charts, styles, macros or workbook relationships. Keep the original file.
- Provide first.xlsx and second.xlsx. This appends rows, not a key join. Headers must match exactly. Formula-looking source text is interpreted by openpyxl when written: review untrusted data before using this simple recipe.
Documentation: openpyxl tutorial and workbook loading options