我正在尝试使用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 writter可能只能写字符串(我不确定它是否正确,但是我不知道如何解决它。有人可以帮我吗?感谢您提供的任何帮助
似乎您可能一直在尝试遵循此示例from the README:
from xml2xlsx import xml2xlsx
template = '<sheet title="test"></sheet>'
f = open('test.xlsx', 'wb')
f.write(xml2xlsx(template))
f.close()
如您所见,template
在这里是str
。而在您的示例中,template
是Document
。
您可以通过Document
将其转换回xml字符串:
Node.to_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()))