如何用Python将XLSX转为XML并以列名为标签?
解决Excel转XML时用列名替代单元格坐标作为标签的问题
咱们核心要做的就是先提取Excel第一行的列名作为XML标签模板,然后后续每一行的数据都对应这些标签来生成元素,而不是用单元格的A1、B1这类坐标。我来一步步帮你修改代码:
关键修改点
- 提取表头列名:先把Excel第一行的所有单元格值存成一个列表,作为后续XML的标签名来源
- 遍历数据行:从第二行开始遍历数据,把每一行的单元格值和对应的表头配对,用表头作为XML标签名
- 调整格式化函数:原来的
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
相关产品推荐
相关产品推荐

