2016-09-07 7 views
1

저는 python을 처음 접했습니다. 실제로 나는 xml을 파싱 할 수 있지만이를 Excel에 쓰는 방법을 모른다.python - excel에 쓰기

샘플 XML :

<?xml version="1.0" encoding="UTF-8"?> 
<breakfast_menu> 
    <food> 
     <name>Belgian Waffles</name> 
     <price>$5.95</price> 
     <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description> 
     <calories>650</calories> 
    </food> 
    <food> 
     <name>Strawberry Belgian Waffles</name> 
     <price>$7.95</price> 
     <description>Light Belgian waffles covered with strawberries and whipped cream</description> 
     <calories>900</calories> 
    </food> 

내 코드 :

import xml.etree.ElementTree as etree 
xmld = etree.parse('simple.xml') 
root = xmld.getroot() 
for child in root: 
    for children in child: 
    print children.tag," : % s" %children.text 

출력 :

name : Belgian Waffles 
price : $5.95 
description : Two of our famous Belgian Waffles with plenty of real maple syrup 
calories : 650 
name : Strawberry Belgian Waffles 
price : $7.95 
description : Light Belgian waffles covered with strawberries and whipped cream 
calories : 900 

하는 등의 Excel로 A 열로

'태그'이 작성 필요 및 '값'을 열로 B enter image description here

이 xlwt 또는 openpyxl 또는 행운 pandas..but 시도 ... pls는이 사이트에서 ..

+0

출력에서 ​​사전을 만든 다음 데이터 프레임을 만들어 엑셀 파일에 씁니다. –

+0

이 문제는 아직 실제입니까, 아니면 답변을 얻었습니까? –

+0

안녕하세요 블라디드 ... 예, openpyxl을 사용해 보았습니다 : "zip ({children.tag}, {children.text})의 행 : ws.append (행) wb.save ("simple.xls ") " 이제 예상대로 출력을 얻을 수 있습니다. 고마워요 !!!! –

답변

1

감사 블라드 .. 내가 아래에 따라 내 코드를 향상 :

import xml.etree.ElementTree as etree 
from openpyxl import Workbook 
xmld = etree.parse('simple.xml') 
root = xmld.getroot() 
wb = Workbook() 
ws = wb.active 
for child in root: 
    for children in child: 
    #print children.tag," : % s" %children.text 
    for row in zip({children.tag},{children.text}): 
     ws.append(row) 
     wb.save("simple.xls") 

지금 내가 예상대로 엑셀 열에 쓰기 성공적으로 해요.

+0

나는 그것이 기뻤다! –