python - 使用 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 写入器只能写入字符串(我不确定它是否正确),但我不明白如何修复它。有人可以帮我吗?感谢您提供的任何帮助
解决方案
看起来您可能一直在尝试遵循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
.
您可以通过以下方式将其转换回 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))
推荐阅读
- vue.js - 有没有办法在这种结构 Vuex 中使用 Promise
- php - Laravel - 找不到类'Collective\Html\HtmlServiceProvider'
- swift - <1> HTTP 加载失败(错误代码:-1003 [12:8])
- javascript - Json格式错误,来自php文件的request_ajax()
- c# - 在 Asp.Net Mvc Web 上将 Windows 窗体客户端与 Tcp 服务器连接
- casting - 声明了一个 List,实现为 LinkedList,不能使用 getLast() 方法
- java - OWL 中类层次结构的节点数据格式 by OWLAPI
- firebase - firebase 实时数据库安全规则以允许特定用户
- python - 变换预测目标
- sql - 使用 distinct 和 row_number 分页时的性能