Python实现XML文件转Excel

了解xml.etree.ElementTree

https://zhuanlan.zhihu.com/p/502584681?utm_id=0

实现代码

运行前请确保对应的库装好

python 复制代码
# encoding: utf-8
import os
import xml.etree.ElementTree as ET
import pandas as pd
from tqdm import tqdm


folder_path = "C:/Users/Administrator/Desktop/新建文件夹"  # 替换为你的文件夹路径
 
# 获取文件夹中的所有文件
file_list = os.listdir(folder_path)
 
# 创建一个空的DataFrame来存储所有XML文件的数据
all_data = pd.DataFrame()
 
# 使用tqdm显示进度条
for file_name in tqdm(file_list, desc="Processing files"):
    if file_name.endswith(".xml"):
        file_path = os.path.join(folder_path, file_name)
         
        # 解析XML文件
        tree = ET.parse(file_path)
        root = tree.getroot()

        # 提取XML数据并转换为DataFram
        xml_data = {}
        for element in root.iter():
            # xml_data[element.tag] = element.attrib
            xml_data.update(element.attrib)

        # print('end')
        # print(xml_data)

        df = pd.DataFrame(xml_data, index=[0])

        # 将DataFrame添加到总的数据集中
        all_data = pd.concat([all_data, df], ignore_index=True)

# 将数据保存为Excel文件
excel_file_path = "C:/Users/Administrator/Desktop/新建文件夹/2011.xlsx"  # 替换为你的输出文件路径,如:/path/to/output/file.xlsx
all_data.to_excel(excel_file_path, index=False)
print('end')
print(all_data)

print("转换完成!Excel文件已保存。")
相关推荐
言乐624 分钟前
Python实现三轴联动根据数据自动打磨镜片模型
开发语言·python
万化冥合30 分钟前
如何批量把 PPT 转成视频?
python·1024程序员节
xiangjiaodalishi43 分钟前
武汉玖叁鹿科技:我们把 GEO 服务做成了可以审计的交付工程
python·1024程序员节
zzu123zsw1 小时前
为什么 Python 做 Agent 总在并发中崩溃?拆解 Blockcell 在 Rust 下的 Host-Cell 隔离与自愈状态机
开发语言·python·rust·大模型·ai agent
jiangliushi61 小时前
GPT-6.1 Sol 免费用:Python 读文件报 ‘gbk‘ codec can‘t decode?加一个参数就好
python·编码·1024程序员节
餐赢计餐饮策划设计1 小时前
如何判断国潮养生设计是否适合自己?
python·1024程序员节
艾灸爱好者2 小时前
艾草精油专业制造商哪3点决定品质高低?
python·1024程序员节
weixin_440401692 小时前
大数据技术-人工智能编程题
大数据·人工智能·python·1024程序员节
“AI国潮设计-小江”2 小时前
AIGC实战:Python+SDXL批量生成英歌舞IP立牌,解锁猪猪蛋糕“反差萌”流量密码(附完整API源码)
开发语言·人工智能·python·prompt·aigc
成信吴彦祖3 小时前
当前专业的无人机RID侦测主站供应商主要有哪些
python·1024程序员节