[英]Read xls file containing xml data in python
An xls file has xml data inside it.一个 xls 文件里面有 xml 数据。 Top portion of the file is shown below:文件的顶部如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">
<Styles>
<Style ss:ID="sDT"><NumberFormat ss:Format="Short Date"/></Style>
</Styles>
<Worksheet ss:Name="XXX">
<Table>
<Row>
<Cell><Data ss:Type="String">Request ID</Data></Cell>
<Cell><Data ss:Type="String">Date</Data></Cell>
<Cell><Data ss:Type="String">XXX ID</Data></Cell>
<Cell><Data ss:Type="String">Customer Name</Data></Cell>
<Cell><Data ss:Type="String">Amount</Data></Cell>
<Cell><Data ss:Type="String">Requested Action</Data></Cell>
<Cell><Data ss:Type="String">Status</Data></Cell>
<Cell><Data ss:Type="String">Transaction ID</Data></Cell>
<Cell><Data ss:Type="String">Merchant UTR</Data></Cell>
</Row>
How can I read it into a Pandas DataFrame using pandas.read_xml.如何使用 pandas.read_xml 将其读入 Pandas DataFrame。 (Any other way of reading it into a DataFrame will also do.) (将它读入 DataFrame 的任何其他方式也可以。)
Note: Have already tried various solutions using read_excel with and without engine ="openpyxl".注意:已经尝试过使用 read_excel 的各种解决方案,无论是否使用引擎 =“openpyxl”。 Different errors are displayed.显示不同的错误。 (See comments below. The comments also contain a link to the same problem faced by others earlier.) (请参阅下面的评论。评论还包含指向其他人之前面临的相同问题的链接。)
Your file is a valid xml file.您的文件是有效的 xml 文件。 I know no automatic converter for that but Excel, but it can easily be parsed as a mere xml file, for example with BeautifulSoul.我知道除了 Excel 之外没有自动转换器,但它可以很容易地被解析为一个纯 xml 文件,例如使用 BeautifulSoul。
If the internal format is simple enough, you could just process the Worksheet
, row
and cell
tags to convert it to a csv file:如果内部格式足够简单,您可以处理Worksheet
、 row
和cell
标签以将其转换为 csv 文件:
from bs4 import BeautifulSoup
import csv
import io
soup = BeautifulSoup(open('file.xxx'))
with open('file.csv', newline='') as fdout:
wr = csv.writer(fdout)
sheet = soup.find('worksheet')
for row in sheet.findAll('row'):
wr.writerow(cell.text for cell in row.findAll('cell'))
Using your sample data, it gives as expected:使用您的示例数据,它按预期给出:
Request ID,Date,XXX ID,Customer Name,Amount,Requested Action,Status,Transaction ID,Merchant UTR
Try to define another engine:尝试定义另一个引擎:
df = pd.read_excel('test.xls', engine='xlrd')
Note that you need to install xlrd
library, eg:请注意,您需要安装xlrd
库,例如:
pip install xlrd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.