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

如何用Python将XLSX转为XML并以列名为标签?

解决Excel转XML时用列名替代单元格坐标作为标签的问题

咱们核心要做的就是先提取Excel第一行的列名作为XML标签模板,然后后续每一行的数据都对应这些标签来生成元素,而不是用单元格的A1、B1这类坐标。我来一步步帮你修改代码:

关键修改点

  1. 提取表头列名:先把Excel第一行的所有单元格值存成一个列表,作为后续XML的标签名来源
  2. 遍历数据行:从第二行开始遍历数据,把每一行的单元格值和对应的表头配对,用表头作为XML标签名
  3. 调整格式化函数:原来的prettify函数参数传错了,需要传入根元素而不是ElementTree对象

修改后的完整代码

from openpyxl import load_workbook
from lxml import etree
from xml.dom import minidom

# 创建XML根元素
root = etree.Element('onlv')
root.set('xmlns', 'http://www.oenorm.at/schema/A2063/2009-06-01')
root.set('xmlns_xsi', 'http://www.w3.org/2001/XMLSchema-instance')
root.set('xsi_schemaLocation', 'http://www.oenorm.at/schema/A2063/2009-06-01 onlv.xsd')
root.set('xmlns_on', 'http://www.oenorm.at/schema/A2063/2009-06-01')
tree = etree.ElementTree(root)

# 加载Excel文件并获取工作表
wb = load_workbook('test3.xlsx')
sheet = wb['Tabelle1']  # 新版openpyxl推荐用名称直接获取,替代get_sheet_by_name

# 提取第一行的表头列名
headers = [cell.value for cell in next(sheet.rows)]

def prettify(xml_element):
    INDENT = "  "
    rough_string = etree.tostring(xml_element, encoding='utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent=INDENT, encoding='utf-8').decode('utf-8')

# 遍历第二行及以后的数据行
for row in sheet.iter_rows(min_row=2):
    # 把当前行的单元格值和表头配对
    for header, cell in zip(headers, row):
        if header is None:  # 跳过空表头的情况
            continue
        # 处理单元格数据类型
        cell_value = cell.value
        if isinstance(cell_value, str):
            etree.SubElement(root, header).text = cell_value
        elif isinstance(cell_value, int):
            etree.SubElement(root, header).text = str(cell_value)
        # 其他类型可以根据需要扩展,比如浮点数、日期等

# 生成格式化后的XML并写入文件
prettified_xmlStr = prettify(root)
with open("filename3.xml", "w", encoding="utf-8") as output_file:
    output_file.write(prettified_xmlStr)

代码说明

  • 用next(sheet.rows)直接获取第一行表头,避免额外的循环判断
  • 用sheet.iter_rows(min_row=2)从第二行开始遍历数据,逻辑更直观
  • 用zip(headers, row)把表头和当前行的单元格一一对应,确保标签和数据精准匹配
  • 优化了文件写入方式,用with语句自动关闭文件,代码更安全简洁
  • 增加了空表头的判断,避免生成无效的XML标签

这样修改后,生成的XML就会用User_ID、Name这类列名作为标签,和你期望的格式完全一致啦!

内容的提问来源于stack exchange,提问作者mccutter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:13:49