我正在尝试使用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:UsersandriPythonProjectsmypyth> py toexcel.py
Traceback (most recent call last):
File "toexcel.py", line 8, in <module>
f.write(xml2xlsx(template))
File "C:UsersandriAppDataLocalProgramsPythonPython37-32libsite-packagesxml2xlsx__init__.py", line 237, in xml2xlsx
return etree.XML(xml, parser, )
File "srclxmletree.pyx", line 3201, in lxml.etree.XML
File "srclxmlparser.pxi", line 1876, in lxml.etree._parseMemoryDocument
ValueError: can only parse strings
我知道xml2xlsx写机可能只能写字符串(我不确定它是否正确),但我不明白如何解决它。有人可以帮我吗?感谢您提供的任何帮助
看起来您可能一直在尝试遵循自述文件中的此示例:
from xml2xlsx import xml2xlsx template = '<sheet title="test"></sheet>' f = open('test.xlsx', 'wb') f.write(xml2xlsx(template)) f.close()
如您所见,template
在这里是一个str
。而在您的示例中,template
是一个Document
。
您可以通过以下方式将其转换回 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))