【问题标题】:python - writing into excelpython - 写入excel
【发布时间】:2016-09-07 18:55:37
【问题描述】:

我是 python 新手。实际上我能够解析一个 xml,但不知道如何将它写入 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里

'tags' 进入 A 列,'values' 进入 B 列 enter image description here

尝试使用 xlwt 或 openpyxl 或 pandas..但没有运气...请帮助..

【问题讨论】:

  • 尝试从您的输出中创建一个字典,然后从中创建一个数据框并将其写入一个 excel 文件。
  • 这个问题是真实的还是你得到了答案?
  • 嗨,弗拉德...是的,尝试使用 openpyxl,例如:" for row in zip({children.tag},{children.text}): ws.append(row) wb.save("simple .xls") " 现在我可以得到预期的输出了。非常感谢!!!!

标签: python-3.x pandas openpyxl xlwt


【解决方案1】:
【解决方案2】:

谢谢弗拉德.. 我已经按照以下改进了我的代码:

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")

现在我按预期成功写入 excel 列。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 2019-08-04
    • 2021-08-30
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    相关资源
    最近更新 更多