Convert Excel records to XML with Python
Create a simple records/record/field document and let ElementTree escape XML characters.
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 openpyxlimport xml.etree.ElementTree as ET
from openpyxl import load_workbook
workbook = load_workbook("input.xlsx", read_only=True, data_only=True)
sheet = workbook["Inventory"]
rows = sheet.iter_rows(values_only=True)
headers = list(next(rows))
if any(not isinstance(key, str) or not key.strip() for key in headers):
raise ValueError("Use nonblank text headers in the first row")
if len(set(headers)) != len(headers):
raise ValueError("Use unique headers")
records = [dict(zip(headers, row)) for row in rows]
workbook.close()
root = ET.Element("records")
for record in records:
item = ET.SubElement(root, "record")
for name, value in record.items():
field = ET.SubElement(item, "field", name=name)
if value is None:
field.set("null", "true")
else:
field.text = str(value)
ET.indent(root)
ET.ElementTree(root).write("output.xml", encoding="utf-8", xml_declaration=True).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.
- This example chooses its own XML structure: null fields use null="true" and other values are text. It is not the browser converter’s typed-field format or a mapping to an external XSD.
Documentation: openpyxl tutorial and workbook loading options