[英]How to read XML data and write to Excel sheet in Python for Selenium Automation
I have a scenario where I need to get the data from XML file and write the same to Excel sheet and use the same sheet for data processing.我有一个场景,我需要从 XML 文件中获取数据并将其写入 Excel 工作表并使用相同的工作表进行数据处理。 I am able to read the data from XML, but not able to insert the same data (records) to an excel file I am using OpenPyExcel for this, please suggest any alternative and help me here.
我能够从 XML 读取数据,但无法将相同的数据(记录)插入到 excel 文件中,我为此使用 OpenPyExcel,请提出任何替代方案并在此处帮助我。 I am not seeing any error though, but nothing is being written to excel sheet
虽然我没有看到任何错误,但没有任何内容写入 excel 表
import xml.etree.ElementTree as ET
import openpyexcel
tree = ET.parse("Test_Cust.xml")
root = tree.getroot()
workbook = openpyexcel.load_workbook("xml_excel.xlsx")
sheet = workbook["Sheet1"]
for items in root.iter():
if items.tag == "Email":
cust_email = items.text
elif items.tag == "CompanyName":
cust_cn = items.text
elif items.tag == "FirstName":
cust_fn = items.text
elif items.tag == "LastName":
cust_ln = items.text
rownum = (sheet.max_row)
print(rownum)
colnum = (sheet.max_column)
print(colnum)
for r in range(2, rownum+1):
for c in range(1, colnum+1):
sheet.cell(row = r, column = c).value = cust_email
sheet.cell(row=r, column=c).value = cust_email
sheet.cell(row=r, column=c).value = cust_email
sheet.cell(row=r, column=c).value = cust_email
workbook.save("xml_excel.xlsx")
print("Done")
Have you tried writing to the cell with this syntax?:您是否尝试过使用此语法写入单元格?:
ws.cell(column=colnum,
row=rownum, value='mydata')
Note: you are saving the sheet in the inner loop.注意:您正在将工作表保存在内循环中。 Slow!
慢的!
Apart from that, this is a valid question: how can you easily read XML formatted data into OpenPYXL?除此之外,这是一个有效的问题:如何轻松地将 XML 格式的数据读入 OpenPYXL? But the question is more about parsing the incoming XML. That done, writing to OpenPYXL seems trivial.
但问题更多是关于解析传入的 XML。完成后,写入 OpenPYXL 似乎微不足道。
(Oops, my mistake: my answer is for OpenPYXL, and may not work with openpyexcel) (糟糕,我的错误:我的答案是针对 OpenPYXL,可能不适用于 openpyexcel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.