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

Python中XML转XLSX报错,求直接转换XML为XLSX的方法

XML转XLSX格式错误的解决方法

问题描述

我尝试用以下Python代码将XML转换为XLSX:

with open(str(Path.cwd())+'\test.xml', "rb") as f1:
    with open(str(Path.cwd())+'\test.xlsx', "wb") as f2:
        f2.write(f1.read())
        f2.close()
xlsx = pd.ExcelFile(str(Path.cwd())+'\test.xlsx')

运行后出现错误:

xlsx = pd.ExcelFile(str(Path.cwd())+'\test.xlsx')
ValueError: Excel file format cannot be determined, you must specify an engine manually.

想问有没有可行的XML转XLSX的方法?


问题原因

你之前的代码只是把XML文件的内容原封不动复制到后缀改名为.xlsx的文件里,本质还是XML格式的内容,Excel和pandas都无法识别这种伪XLSX文件,所以报错。


可行转换方案

方案一:用pandas解析XML后写入XLSX

适用于结构规整的表格型XML(比如每个数据节点对应一行),示例代码如下:

import pandas as pd
import xml.etree.ElementTree as ET
from pathlib import Path

# 解析XML文件
tree = ET.parse(Path.cwd() / "test.xml")
root = tree.getroot()

# 提取XML中的数据到字典列表
data_rows = []
for row_node in root.findall("row"):
    row_dict = {}
    for child in row_node:
        row_dict[child.tag] = child.text
    data_rows.append(row_dict)

# 转换为DataFrame并写入XLSX
df = pd.DataFrame(data_rows)
df.to_excel(Path.cwd() / "test.xlsx", index=False)

# 验证读取
xlsx_file = pd.ExcelFile(Path.cwd() / "test.xlsx")
print(xlsx_file.sheet_names)

方案二:用openpyxl手动构建Excel文件

如果XML结构复杂,需要自定义单元格样式或布局,可使用openpyxl:

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

# 解析XML
tree = ET.parse(Path.cwd() / "test.xml")
root = tree.getroot()

# 创建Excel工作簿和工作表
wb = Workbook()
ws = wb.active

# 写入表头(假设第一个row节点的子元素为表头)
header = [child.tag for child in root.find("row")]
ws.append(header)

# 逐行写入数据
for row_node in root.findall("row"):
    row_values = [child.text for child in row_node]
    ws.append(row_values)

# 保存XLSX文件
wb.save(Path.cwd() / "test.xlsx")

注意:如果你的XML结构不是标准表格型,需要根据实际节点结构调整数据提取逻辑,先把XML数据整理成二维表格形式,再写入Excel。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 13:28:11