create a csv file which is Excel friendly format.

import xml.etree.ElementTree as ET
from os import listdir


xml_lst = [f for f in listdir() if f.startswith('xml')]
fields = ['RecordID','I_25Hz_1s','I_75Hz_2s'] # TODO - add rest of the fields
with open('out.csv','w') as f:
  f.write(','.join(fields) + '\n')
  for xml in xml_lst:
    root = ET.parse(xml)
    values = [root.find(f'.//{f}').text for f in fields]
    f.write(','.join(values) + '\n')

output

RecordID,I_25Hz_1s,I_75Hz_2s
Madird01,56.40,0.36
London01,56.40,0.36
Answer from balderman on Stack Overflow
🌐
Python.org
discuss.python.org › python help
Convert xml to excel/csv - Python Help - Discussions on Python.org
October 15, 2022 - Please help me in converting XML file into excel/csv. Thank you in advance.
Top answer
1 of 3
2

create a csv file which is Excel friendly format.

import xml.etree.ElementTree as ET
from os import listdir


xml_lst = [f for f in listdir() if f.startswith('xml')]
fields = ['RecordID','I_25Hz_1s','I_75Hz_2s'] # TODO - add rest of the fields
with open('out.csv','w') as f:
  f.write(','.join(fields) + '\n')
  for xml in xml_lst:
    root = ET.parse(xml)
    values = [root.find(f'.//{f}').text for f in fields]
    f.write(','.join(values) + '\n')

output

RecordID,I_25Hz_1s,I_75Hz_2s
Madird01,56.40,0.36
London01,56.40,0.36
2 of 3
1

When you need to iterate over files in folder with similar names one of the ways could be make a pattern and use glob. To make sure that returned path is file you can use isfile().

Regarding XML, I see that basically you need to write values of every terminal tag in column with name of this tag. As you have various files you can create tag-value dictionaries from each file and store them into ChainMap. After all files processed you can use DictWriter to write all data into final csv file.

This method is much more safe and flexible then use static column names. Firstly program will collect all possible tag(column) names from all files, so in case if XML doesn't have such a tag or have some extra tags it won't throw an exception and all data will be saved.

Code:

import xml.etree.ElementTree as ET
from glob import iglob
from os.path import isfile, join
from csv import DictWriter
from collections import ChainMap

xml_root = r"C:\data\Desktop\Blue\XML-files"
pattern = "xmlfile_*"
data = ChainMap()
for filename in iglob(join(xml_root, pattern)):
    if isfile(filename):
        tree = ET.parse(filename)
        root = tree.getroot()
        temp = {node.tag: node.text for node in root.iter() if not node}
        data = data.new_child(temp)

with open(join(xml_root, "data.csv"), "w", newline="") as f:
    writer = DictWriter(f, data)
    writer.writeheader()
    writer.writerows(data.maps[:-1])  # last is empty dict

Upd. If you want to use xlsx format instead of csv you have to use third-party library (e.g. openpyxl). Example of usage:

from openpyxl import Workbook

...

wb = Workbook(write_only=True)
ws = wb.create_sheet()
ws.append(list(data))  # write header
for row in data.maps[:-1]:
    ws.append([row.get(key, "") for key in data])
wb.save(join(xml_root, "data.xlsx"))
Discussions

How to parse XML into an excel sheet?
Depending on the complexity of the xml, the easiest way might be to simply read into a pandas dataframe and write it back out as Excel. https://pandas.pydata.org/docs/reference/api/pandas.read_xml.html# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html More on reddit.com
🌐 r/learnpython
2
3
December 3, 2021
Python extract data from xml and save it to excel - Stack Overflow
I would like to extract some data from an XML file and save it in a table format, such as XLS or DBF. Here is XML file i have: More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
Can Python read/write XML and Excel XLSX files?
I did 15 minutes of a Python tutorial ... similar to Perl. Thank you for your time! ... For xlsx see here. For XML see xlml or lxml. dancergraham (Graham Knapp) January 9, 2024, 1:30pm ... You can also use the pandas library if you are dealing with tabular data - it has good support for excel import and ... More on discuss.python.org
🌐 discuss.python.org
0
0
January 9, 2024
Convert Excel XML to .xlsx with python
Hello guys, so i have this XML file which i can open pretty easily using Excel this is the file, but i want to convert it to xlsx or any compatible format to be able to use openpyxl module to it so that i can read it easily, is there any way to do this on python? More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
September 29, 2020
🌐
GitHub
github.com › vrushabhkaushik › XML-to-Excel-Conversion
GitHub - vrushabhkaushik/XML-to-Excel-Conversion: The python script reads the XML file name from user's input, and then using data frame, it writes the data to an Excel sheet
The python script reads the XML file name from user's input, and then using data frame, it writes the data to an Excel sheet - vrushabhkaushik/XML-to-Excel-Conversion
Starred by 5 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
PyPI
pypi.org › project › xml2xlsx
xml2xlsx · PyPI
This is a merely an xml parser translating mostly linearly to worksheet, rows and finally cells of the Excel workbook.
      » pip install xml2xlsx
    
Published   Sep 16, 2024
Version   1.0.2
🌐
Reddit
reddit.com › r/learnpython › how to parse xml into an excel sheet?
r/learnpython on Reddit: How to parse XML into an excel sheet?
December 3, 2021 -

Bare with me, as I'm a novice with python, but basically, I am trying to take an XML file, and plop it into an existing excel workbook in a specific sheet. I know I have done this successfully before, but cannot find the file where I did, nor can I remember how I did.

When I do it manually, the process is pretty straight forward - download the XML file, open it with excel, copy and paste as text into the sheet. Just hoping someone could help me get started here. Thanks so much for your time.

To be more specific this is the layout of the XML file:

<products>

<product active="1" on_sale="0" discountable="1">

<sku>GG1234</sku>

<name><![CDATA[ Product Name Here ]]></name>

<description><![CDATA[Product Description Here ]]></description>

<keywords></keywords>

<price>8.9</price>

<stock_quantity>220</stock_quantity>

<reorder_quantity>0</reorder_quantity>

<height>4.25</height>

<length>1.25</length>

<diameter>2.5</diameter>

<weight>0.53</weight>

<color></color>

<material>Material Here/material>

<barcode>0000000000</barcode>

<release_date>2010-02-19</release_date>

<images>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

<image>/path/path.jpg</image>

</images>

<categories>

<category code="518" video="0" parent="0">Category 1</category>

<category code="525" video="0" parent="528">Category 2</category>

<category code="138" video="0" parent="0">Category 3</category>

<category code="552" video="0" parent="528">Category 4</category>

</categories>

<manufacturer code="AC" video="0">Manufact</manufacturer>

<type code="CL" video="0">Product Type</type>

</product> . . . . .

<products>

What I need is for the follow values to populate the top row as the header of the excel file:

active
on_sale
disctountable
sku
name
description
keywords
price
stock_quantity
reorder_quantity
height
length
diameter
weight
color
material
barcode
release_date
image
category
manufacturer
code2
video3
type
code4
video5

And then their respective values to populate the cells going downward in the columns.

Hope that makes sense

🌐
e-iceblue
e-iceblue.com › Tutorials › Python › Spire.XLS-for-Python › Program-Guide › Conversion › Python-Convert-XML-to-Excel-and-XML-to-PDF.html
Python: Convert XML to Excel and XML to PDF
Learn how to convert XML to Excel and XML to PDF using Spire.XLS for Python. Master the process with step-by-step instructions and tips for efficient data transformation.
🌐
EasyXLS
easyxls.com › manual › tutorials › python › convert-xml-spreadsheet-to-excel.html
Convert XML Spreadsheet to Excel file in Python | EasyXLS Guide
Code sample Python: Convert XML Spreadsheet to Excel file in Python by EasyXLS library. XLSX, XLSM, XLSB, XLS in Python
Find elsewhere
🌐
Aspose
products.aspose.com › aspose.cells › python via .net › conversion › xml to excel
Python XML to EXCEL - XML to EXCEL Converter | products.aspose.com
November 13, 2025 - Aspose Excel. This comprehensive solution provides Python developers with a fully integrated approach to convert XML to EXCEL format, enabling seamless saving of XML data into EXCEL format using the Aspose.Cells library, all through efficient ...
🌐
Like Geeks
likegeeks.com › home › python › pandas › export xml to excel using python pandas
Export XML to Excel using Python Pandas
April 27, 2025 - You’ll learn how to parse basic ... You can export XML files to Excel by reading the XML using Pandas read_xml() and then exporting the result DataFrame to Excel using Pandas to_excel()....
🌐
Aspose
blog.aspose.com › aspose blog › convert xml to excel in python
Convert XML to Excel Python | Export XML to Excel in Python
March 15, 2024 - Convert XML to Excel in Python. Export data from an XML file to Excel programmatically in Python using Aspose.Cells for Python API.
🌐
Python.org
discuss.python.org › python help
Can Python read/write XML and Excel XLSX files? - Python Help - Discussions on Python.org
January 9, 2024 - I did 15 minutes of a Python tutorial and it looks very similar to Perl. Thank you for your time! ... For xlsx see here. For XML see xlml or lxml. dancergraham (Graham Knapp) January 9, 2024, 1:30pm ... You can also use the pandas library if you are dealing with tabular data - it has good support for excel import and export, it is reasonably quick and flexible for handling bulk operations on columns of data and it can handle some simple custom xml formats IO tools (text, CSV, HDF5, …) — pandas 2.1.4 documentation
🌐
Quora
quora.com › How-can-I-convert-XML-to-Excel-using-Python-scripting
How to convert XML to Excel using Python scripting - Quora
Answer: Hi you can use regular expression to extract data. And then you can write the got results into the excel through the python script itself. Re module is used for extracting data and excel module to open and write into the excel file
🌐
freeCodeCamp
forum.freecodecamp.org › python
Convert Excel XML to .xlsx with python - Python - The freeCodeCamp Forum
September 29, 2020 - Hello guys, so i have this XML file which i can open pretty easily using Excel this is the file, but i want to convert it to xlsx or any compatible format to be able to use openpyxl module to it so that i can read it eas…
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-convert-excel-to-xml-format-in-python
How to Convert Excel to XML Format in Python? | GeeksforGeeks
March 21, 2024 - However, for tasks like data analysis or spreadsheet editing, CSV (Comma-Separated Values) is far more user-friendly and easier to work with.To make XML data easier to process, we often convert it to a CSV file. ... In this article, we will see how to convert a PDF to Excel or CSV File Using Python.
🌐
Aspose
kb.aspose.com › cells › python › how-to-convert-xml-to-excel-file-using-python
How to Convert XML to Excel File using Python
July 14, 2023 - First of all, create an instance of the Workbook class to load the source XML file. Next, invoke the save method to render the output Excel file while specifying the XLSX file format.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-xml-to-csv-in-python
Convert XML to CSV in Python - GeeksforGeeks
July 23, 2025 - Parse the XML file. Extract the relevant data. Store it into a pandas DataFrame. Export the DataFrame to a CSV file.
🌐
Medium
medium.com › @soderholm.conny › how-to-generate-an-xml-file-from-excel-with-python-96cff7b768db
How to generate an XML file from Excel with Python | by Soderholm Conny | Medium
August 1, 2023 - We use a list comprehension to get all the values from the cells. Next, we are adding the babies. Notice the use of the With tag and text. When we are finished we indent our result with Yattags indent method. Finally, we save our file. The output should look like below. Notice that I only included two babies in the output. <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"></xs:schema> <Babies> <Baby> <Name> GERALDINE </Name> <Gender> FEMALE </Gender> <year> 2011 </year> <count> 13 </count> <rank> 75 </rank> </Baby> <Baby> <Name> GIA </Name> <Gender> FEMALE </Gender> <year> 2011 </year> <count> 21 </count> <rank> 67 </rank> </Baby> </Babies>
🌐
Adimian
adimian.com › blog › fast-xlsx-parsing-with-python
Fast Xlsx Parsing With Python - Adimian: Sustainable Python Software Development & Consultancy
January 2, 2024 - The XSLT method is twice as fast as pandas’ read_excel. The benchmarks were run on a large sheet of 537 lines and 341 columns: $ python fast_xlsx_parsing.py xslt: 3.311 pandas: 6.248 · Incidentally, googling for "xslt" "pandas" "csv" returns this unanswered StackOverflow question with the same approach, as usual it’s easier to find a solution when you already know the answer.