Skip to content

Commit d9d9b76

Browse files
committed
commit 0018
1 parent d3d9730 commit d9d9b76

3 files changed

Lines changed: 35 additions & 0 deletions

File tree

darcycool/0018/city.xls

5.5 KB
Binary file not shown.

darcycool/0018/city.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version='1.0' encoding='utf8'?>
2+
<root><citys>{
3+
"1": "上海",
4+
"2": "北京",
5+
"3": "成都"
6+
}</citys></root>

darcycool/0018/excel2xml.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# -*- coding: utf-8 -*-
2+
# 第 0018 题: 将 第 0015 题中的 city.xls 文件中的内容写到 city.xml 文件中
3+
import xlrd
4+
from collections import OrderedDict
5+
import json
6+
7+
import xml.etree.cElementTree as ET
8+
9+
wb = xlrd.open_workbook('city.xls')
10+
sheet = wb.sheet_by_index(0)
11+
number_of_row = sheet.nrows
12+
number_of_col = sheet.ncols
13+
14+
city = OrderedDict()
15+
16+
for row in range(number_of_row):
17+
city[sheet.cell(row, 0).value] = sheet.cell(row, 1).value
18+
19+
print(city)
20+
json_str = json.dumps(city, ensure_ascii=False, indent=4)
21+
print(json_str)
22+
23+
root = ET.Element('root')
24+
cities = ET.SubElement(root, 'citys')
25+
26+
cities.text = json_str
27+
28+
tree = ET.ElementTree(root)
29+
tree.write('city.xml', encoding='utf8', xml_declaration=True)

0 commit comments

Comments
 (0)