首页 > 解决方案 > 使用 minidom 和 xml2xlsx 从 xml 转换为 xlsl 不起作用

问题描述

我正在尝试使用 Python 将多个 XML 文件转换为 xlsl,我找到了一个名为 xml2xlsx 的库,它可以帮助我做到这一点!我的想法是使用 minidom 库打开 XML 文件,将其保存在变量中,然后将其写入 xlsx 文件。到目前为止,我已经编写了以下代码:

from xml2xlsx import xml2xlsx
from xml.dom import minidom
template = open('file.xml','r')
xmldoc = minidom.parse(template)
template.close()

f = open('test.xlsx', 'wb')
f.write(xml2xlsx(template))
f.close()

问题是,在运行它时,我收到一条错误消息:

PS C:\Users\andri\PythonProjects\mypyth> py toexcel.py
Traceback (most recent call last):
  File "toexcel.py", line 8, in <module>
    f.write(xml2xlsx(template))
  File "C:\Users\andri\AppData\Local\Programs\Python\Python37-32\lib\site-packages\xml2xlsx\__init__.py", line 237, in xml2xlsx
    return etree.XML(xml, parser, )
  File "src\lxml\etree.pyx", line 3201, in lxml.etree.XML
  File "src\lxml\parser.pxi", line 1876, in lxml.etree._parseMemoryDocument
ValueError: can only parse strings

我知道可能 xml2xlsx 写入器只能写入字符串(我不确定它是否正确),但我不明白如何修复它。有人可以帮我吗?感谢您提供的任何帮助

标签: pythonxmlfileminidom

解决方案


看起来您可能一直在尝试遵循README 中的这个示例:

from xml2xlsx import xml2xlsx
template = '<sheet title="test"></sheet>'
f = open('test.xlsx', 'wb')
f.write(xml2xlsx(template))
f.close()

如您所见,templatestr这里。而在您的示例中,templateDocument.

您可以通过以下方式将其转换回 xml 字符串Node.to_xml

from xml2xlsx import xml2xlsx
from xml.dom import minidom

with open('file.xml') as xml_file:
    template = minidom.parse(xml_file)

with open('test.xlsx', 'wb') as xlsx_file:
    xlsx_file.write(xml2xlsx(template.to_xml()))

或者完全跳过这minidom一步:

from xml2xlsx import xml2xlsx

with open('file.xml') as xml_file:
    template = xml_file.read()

with open('test.xlsx', 'wb') as xlsx_file:
    xlsx_file.write(xml2xlsx(template))

推荐阅读