Create sub tables in Excel sheet from an xml using python element tree

穿精又带淫゛_ 提交于 2020-01-11 13:18:59

问题


<?xml version="1.0" encoding="UTF-8"?>

-<Metrics>    

  -<File name="N:/Users/Source/Callbacks.c">    

    -<Entity name="N:/Users/Source/CAN_Callbacks.c" type="file">

       <Metric name="STTDE" value="2.205"/>

       <Metric name="STM28" value="27"/>

       <Metric name="STTDO" value="1.999"/>

     </Entity>

    -<Entity name="ApplNwmBusoff" type="function">

       <Metric name="STM07" value="1"/>

       <Metric name="STUNV" value="1"/>

       <Metric name="STSUB" value="1"/>

     </Entity>

  </File>

</Metrics>

This is the xml code. I want to create subtables in Excel sheet as follows:

This is my code:

import os
import xml.etree.ElementTree as ET
import pandas as pd

dir = r"C:\Users\HIL Tester\projt\prqa\reports\projt_MDR_13062017_112431.xml"
file_name = []
metric_name = []
metric_value = []
table_end_indices = []
metric_name_lists = []
metric_value_lists = []
main_list = []





tree = ET.parse(dir)
root = tree.getroot()

for child in root[0].iter('Entity'):
    file_name.append(child.get('name'))


for table_ind in range(len(root[0])):
    for c in root[0][table_ind].iter('Metric'):
        metric_name.append(c.get('name'))#all the headers are appended to metric name list
        metric_value.append(c.get('value'))#all the values are appended to metric value list


data_frame1 = pd.DataFrame(file_name)
data_frame2 = pd.DataFrame(metric_name)
data_frame3 = pd.DataFrame(metric_value)
frames = [data_frame1, data_frame2, data_frame3]
result = pd.concat(frames)
result=result.transpose()
writer = pd.ExcelWriter(r'N:\Users\xml\report.xlsx')
result.to_excel(writer, 'xml_report')
writer.save()

But this code generates table in this format.I want to create tables in the above mentioned format. Can someone help me please?


回答1:


Solution using openpyxl, for instance:

from openpyxl import Workbook

wb = Workbook()
ws = wb.worksheets[0]
ws.title = 'xml_report'

tree = ET.parse(xml)
root = tree.getroot()

for entity in root[0].iter('Entity'):
    subtable_header = []
    subtable_header.append(entity.get('name'))
    subtable_values = ['']
    for metric in entity.iter('Metric'):
        subtable_header.append(metric.get('name'))
        subtable_values.append(metric.get('value'))

    ws.append(subtable_header)
    ws.append(subtable_values)

wb.save('N:\Users\xml\report.xlsx')

Output:

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2



来源:https://stackoverflow.com/questions/44553403/create-sub-tables-in-excel-sheet-from-an-xml-using-python-element-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!