You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定目录下的多个XML文件批量转换为横向排列的Excel文件

问题需求

我本地有一个存放多个XML文件的目录,其中两个示例文件内容如下:

<Record>
        <RecordID>Madird01</RecordID>
        <Location>Madird</Location>
        <Date>07-09-2020</Date>
        <Time>07u43m55s</Time>
        <Version>2.0.1</Version>
        <Version_2>v1.9</Version_2>
    <Max_30e>
        <I_25Hz_1s>56.40</I_25Hz_1s>
        <I_25Hz_2s>7.44</I_25Hz_2s>
    </Max_30e>
    <Max_30e>
        <I_75Hz_1s>1.56</I_75Hz_1s>
        <I_75Hz_2s>0.36</I_75Hz_2s>
    </Max_30e>
</Record>

另一个示例文件内容如下:

<Record>
        <RecordID>London01</RecordID>
        <Location>London</Location>
        <Date>07-09-2020</Date>
        <Time>08u53m45s</Time>
        <Version>2.0.1</Version>
        <Version_2>v1.9</Version_2>
    <Max_30e>
        <I_25Hz_1s>56.40</I_25Hz_1s>
        <I_25Hz_2s>7.44</I_25Hz_2s>
    </Max_30e>
    <Max_30e>
        <I_75Hz_1s>1.56</I_75Hz_1s>
        <I_75Hz_2s>0.36</I_75Hz_2s>
    </Max_30e>
</Record>

我需要将这些XML文件的内容按照横向排列的格式转换为Excel文件,预期效果见:
预期效果示意图
我此前尝试先将XML转换为CSV字符串再转为Excel,但遇到阻碍,希望找到更简便的实现方法,当前编写的代码如下:

import xml.etree.ElementTree as ET
import os

xml_root = r'c:\data\Desktop\Blue\XML-files'

for file in os.listdir(xml_root):
    xml_file_path = os.path.join(xml_root, file)
    
    tree = ET.parse(xml_file_path)
    root = tree.getroot()
    tree = ET.ElementTree(root)

    for child in root:
        mainlevel = child.tag
        xmltocsv = ''
        for elem in root.iter():
            if elem.tag == root.tag:
                continue
            if elem.tag == mainlevel:
                xmltocsv = xmltocsv + '\n'
            xmltocsv = xmltocsv + str(elem.tag).rstrip() + str(elem.attrib).strip() + ';' + str(elem.text).rstrip() + ';'
解决方案

直接使用pandas+openpyxl实现转换,无需手动拼接CSV,逻辑简单不易出错:

  • 安装依赖库:
pip install pandas openpyxl
  • 完整实现代码:
import xml.etree.ElementTree as ET
import os
import pandas as pd

# 替换为你的XML文件存放目录
xml_root = r'c:\data\Desktop\Blue\XML-files'
all_rows = []

for file in os.listdir(xml_root):
    # 仅处理XML格式文件,避免其他文件干扰
    if not file.lower().endswith('.xml'):
        continue
    xml_file_path = os.path.join(xml_root, file)
    root = ET.parse(xml_file_path).getroot()
    # 存储单份XML对应的一行数据
    current_row = {}
    for child in root:
        # 处理顶层无嵌套的字段
        if len(child) == 0:
            current_row[child.tag] = child.text.strip() if child.text else ''
        # 处理Max_30e这类嵌套层级的字段
        else:
            for sub_child in child:
                current_row[sub_child.tag] = sub_child.text.strip() if sub_child.text else ''
    all_rows.append(current_row)

# 导出为Excel文件,生成的output.xlsx会保存在代码运行目录
df = pd.DataFrame(all_rows)
df.to_excel('output.xlsx', index=False)

代码运行后会生成符合要求的Excel文件,每份XML对应一行数据,所有字段自动对齐为列,无需额外手动处理格式。


内容的提问来源于stack exchange,提问作者Al-Andalus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:15:07