转换xml至表格

前言

最近在做一个项目,需要将xml文件中的数据转换为表格,方便后续的操作。
以下是我写的代码,希望对大家有所帮助。

代码

单个xml转换

import xml.etree.ElementTree as ET
from openpyxl import Workbook

def parse_xml_to_excel(xml_file, excel_file):
# 创建一个新的 Excel 工作簿
wb = Workbook()
sheet = wb.active

# 打开 XML 文件并解析
tree = ET.parse(xml_file)
root = tree.getroot()

# 设置命名空间,用于在查找元素时指定命名空间
ns = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}

# 遍历所有 <url> 元素
row_index = 1
for url in root.findall('ns:url', ns):
loc = url.find('ns:loc', ns).text
lastmod = url.find('ns:lastmod', ns).text if url.find('ns:lastmod', ns) is not None else ''

# 将 loc 和 lastmod 写入 Excel 单元格
sheet.cell(row=row_index, column=1, value=loc)
sheet.cell(row=row_index, column=2, value=lastmod)

row_index += 1

# 保存 Excel 文件
wb.save(excel_file)
print(f"XML 文件已成功转换为 Excel 文件:{excel_file}")

# 指定输入的 XML 文件和输出的 Excel 文件路径
input_xml_file = 'S:/Users/26370/Desktop/Down/mineleak.pro/mineleak.pro.xml'
output_excel_file = 'output.xlsx'

# 调用函数将 XML 文件转换为 Excel 文件
parse_xml_to_excel(input_xml_file, output_excel_file)

文件夹下所有xml转换

将文件夹下所有xml存入一张表格中,并设置如果超过3万条数据
import os
import xml.etree.ElementTree as ET
from openpyxl import Workbook

def parse_xml_to_excel(xml_folder, max_rows_per_sheet, output_excel_prefix):
    file_count = 1
    row_index = 2  # 从第二行开始写入数据

    # 创建第一个 Excel 工作簿
    wb = Workbook()
    sheet = wb.active
    sheet.cell(row=1, column=1, value='URL')
    sheet.cell(row=1, column=2, value='Last Modified')

    # 遍历指定文件夹中的所有 XML 文件
    for filename in os.listdir(xml_folder):
        if filename.endswith('.xml'):
            xml_file = os.path.join(xml_folder, filename)

            try:
                # 打开 XML 文件并解析
                tree = ET.parse(xml_file)
                root = tree.getroot()

                # 设置命名空间
                ns = {'ns': 'http://www.sitemaps.org/schemas/sitemap/0.9'}

                # 遍历所有 <url> 元素
                for url in root.findall('ns:url', ns):
                    loc = url.find('ns:loc', ns).text
                    lastmod = url.find('ns:lastmod', ns).text if url.find('ns:lastmod', ns) is not None else ''

                    # 将 loc 和 lastmod 写入 Excel 单元格
                    sheet.cell(row=row_index, column=1, value=loc)
                    sheet.cell(row=row_index, column=2, value=lastmod)

                    row_index += 1

                    # 检查是否超过最大行数限制,超过则创建新的 Excel 工作簿
                    if row_index > max_rows_per_sheet:
                        output_excel_path = f'{output_excel_prefix}_{file_count}.xlsx'
                        wb.save(output_excel_path)
                        print(f"已保存至 Excel 文件:{output_excel_path}")

                        # 创建新的 Excel 工作簿
                        file_count += 1
                        wb = Workbook()
                        sheet = wb.active
                        sheet.cell(row=1, column=1, value='URL')
                        sheet.cell(row=1, column=2, value='Last Modified')
                        row_index = 2  # 重置行索引

            except ET.ParseError as e:
                print(f"解析 XML 文件 '{xml_file}' 出错: {e}")

    # 保存最后一个 Excel 文件
    output_excel_path = f'{output_excel_prefix}_{file_count}.xlsx'
    wb.save(output_excel_path)
    print(f"最后一部分数据已保存至 Excel 文件:{output_excel_path}")

# 指定包含 XML 文件的文件夹路径、每个表格的最大行数和输出的 Excel 文件前缀
xml_folder_path = 'S:/Users/26370/Desktop/Down/blackspigot.com'
max_rows_per_sheet = 30000
output_excel_prefix = 'blackspigot'

# 调用函数将指定文件夹中的所有 XML 文件内容提取到一个或多个 Excel 文件中
parse_xml_to_excel(xml_folder_path, max_rows_per_sheet, output_excel_prefix)