讀取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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM