我正在使用 ElementTree 读取 xml 文件,但有一个单元格无法读取其数据。
我调整了我的文件以制作一个可重现的示例,如下所示:
from xml.etree import ElementTree
import io
xmlf = """<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook ss:ResourcesPackageName="" ss:ResourcesPackageVersion="" xmlns="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
xmlns:html="http://www.w3.org/TR/REC-html40">
<Worksheet ss:Name="DigitalOutput" ss:IsDeviceType="true">
<Row ss:AutoFitHeight="0">
<Cell><Data ss:Type="String">A</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">B</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
<Cell><Data ss:Type="String">C</Data><NamedCell ss:Name="_FilterDatabase"/></Cell>
<Cell ss:Index="7"><ss:Data ss:Type="String"
xmlns="http://www.w3.org/TR/REC-html40"><Font html:Color="#000000">CAN'T READ </Font><Font>THIS</Font></ss:Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
<Cell ss:Index="10"><Data ss:Type="String">D</Data><NamedCell
ss:Name="_FilterDatabase"/></Cell>
</Row>
</Worksheet>
</Workbook>"""
ss = "urn:schemas-microsoft-com:office:spreadsheet"
worksheet_label = '{%s}Worksheet' % ss
row_label = '{%s}Row' % ss
cell_label = '{%s}Cell' % ss
data_label = '{%s}Data' % ss
tree = ElementTree.parse(io.StringIO(xmlf))
root = tree.getroot()
for ws in root.findall(worksheet_label):
for table in ws.findall(row_label):
for c in table.findall(cell_label):
data = c.find(data_label)
print(data.text)
输出是:
A
B
C
None
D
因此,第四个单元格未被读取。你能帮我解决这个问题吗?
Question:使用 ElementTree 读取 .xml 等电子表格
文档:lxml.etree 教程 - 命名空间 https://lxml.de/tutorial.html#namespaces
-
定义namespaces
used
ns = {'ss':"urn:schemas-microsoft-com:office:spreadsheet",
'html':"http://www.w3.org/TR/REC-html40"
}
-
Use the namespaces
with find(.../findall(...
tree = ElementTree.parse(io.StringIO(xmlf))
root = tree.getroot()
for ws in root.findall('ss:Worksheet', ns):
for table in ws.findall('ss:Row', ns):
for c in table.findall('ss:Cell', ns):
data = c.find('ss:Data', ns)
if data.text is None:
text = []
data = data.findall('html:Font', ns)
for element in data:
text.append(element.text)
data_text = ''.join(text)
print(data_text)
else:
print(data.text)
Output:
A
B
C
CAN'T READ THIS
D
使用 Python 测试:3.5
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)