读取xml文件,写入excel

  在上一篇 Python写xml文件 已经将所有订单写入xml文件,这一篇我们把xml文件中的内容读出来,写入excel文件。

  输入xml格式:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <orderlist>
 3     <order>
 4         <customer>姓名1</customer>
 5         <phone>123456</phone>
 6         <address>成都</address>
 7         <count>2</count>
 8     </order>
 9     <order>
10         <customer>姓名2</customer>
11         <phone>234567</phone>
12         <address>成都</address>
13         <count>5</count>
14     </order>
15     <order>
16         <customer>姓名3</customer>
17         <phone>345678</phone>
18         <address>成都</address>
19         <count>1</count>
20     </order>
21 </orderlist>
View Code

  输出excel格式(这里按点餐次数进行的降序排序):

  工具库选择:beautifulsoup+lxml用于处理xml文件(当然也可直接使用lxml), xlsxwriter用于写excel文件。

  思路也比较简单:找出xml文件中的每一个<order>,然后进行降序排序,再将每一个order信息写入excel文件,每个order一行。

  代码如下:

 1 # coding: utf-8
 2 
 3 import bs4
 4 import xlsxwriter
 5 
 6 # 读取xml文件,写入excel
 7 def xmlToExcel(file_xml, file_excel):
 8     # 打开xml文件,并以此创建一个bs对象
 9     xml = open(file_xml, 'r')
10     doc = bs4.BeautifulSoup(xml, 'xml')
11 
12     # 创建一个excel文件,并添加一个sheet,命名为orders
13     workbook = xlsxwriter.Workbook(file_excel)
14     sheet = workbook.add_worksheet('orders')
15 
16     # 设置粗体
17     bold = workbook.add_format({'bold': True})
18 
19     # 先在第一行写标题,用粗体
20     sheet.write('A1', u'姓名', bold)
21     sheet.write('B1', u'电话', bold)
22     sheet.write('C1', u'点餐次数', bold)
23     sheet.write('D1', u'地址', bold)
24 
25     # 筛选出所有的<order>,这里使用的是CSS选择器
26     order = doc.select('order')
27 
28     # 以每个order的count元素,对order进行降序排序
29     sort_key = lambda a: int(a.count.text)
30     order.sort(key=sort_key, reverse=True)
31 
32     # 行号,具体订单信息从第二行开始
33     row = 2
34     # 将每一个订单写入excel
35     for x in order:
36         # 提取出具体信息
37         name = x.customer.text
38         phone = x.phone.text
39         cnt = x.count.text
40         addr = x.address.text
41 
42         # 将具体信息写入excel
43         sheet.write('A%d' % row, name)
44         sheet.write('B%d' % row, phone)
45         sheet.write('C%d' % row, cnt)
46         sheet.write('D%d' % row, addr)
47 
48         row += 1
49 
50     # 关闭文件
51     xml.close()
52     workbook.close()
53 
54 # 测试代码
55 if __name__ == '__main__':
56     file1 = 'hh.xml'
57     file2 = 'hehe.xlsx'
58 
59     xmlToExcel(file1, file2)

 

posted @ 2016-07-30 23:13  oceany  阅读(5289)  评论(1编辑  收藏  举报