lyh916

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

参考链接:

https://www.cnblogs.com/zjzyh/p/5769069.html

https://blog.csdn.net/Nick_Li_/article/details/90139383

 

关于collections.OrderedDict():https://www.cnblogs.com/gide/p/6370082.html

是一种有序的字典

 

代码如下:

excel2json.py

 1 import xlrd
 2 import collections
 3 import json
 4 import codecs
 5 
 6 # excelPath:读取的excel路径
 7 # jsonPath:输出的json路径
 8 # keyRow:key所处的行
 9 # typeRow:type所处的行
10 # valueRow:value开始的行
11 def excel2json(excelPath, jsonPath, keyRow=1, typeRow=2, valueRow=3):
12     wb = xlrd.open_workbook(excelPath)
13     sheet = wb.sheet_by_index(0)
14     keys = sheet.row_values(keyRow)
15     types = sheet.row_values(typeRow)
16     data = {}
17     
18     for row in range(valueRow,sheet.nrows):
19         rowData = sheet.row_values(row)
20         temp = collections.OrderedDict()
21         for col in range(sheet.ncols):
22             key = keys[col]
23             colType = types[col]
24             value = rowData[col]
25             if colType == 'json':
26                 temp[key] = json.loads(value)
27             elif colType == 'int':
28                 temp[key] = int(value)
29             else: #string float在读取excel时已区分
30                 temp[key] = value
31         data[int(rowData[0])] = temp
32 
33     jsonStr = json.dumps(data,ensure_ascii=False,indent=4)
34     with codecs.open(jsonPath,"w","utf-8") as f:
35         f.write(jsonStr)
36 
37     return jsonStr

 

测试:

test.py

1 import excel2json
2 import json2lua
3 import json
4 
5 jsonStr = excel2json.excel2json("./xls/zz.xls", "./json/zz.json")
6 print(jsonStr)

 

表格:

 

输出:

 1 {
 2     "2": {
 3         "id": 2,
 4         "name": "",
 5         "desc": [
 6             [
 7                 1,
 8                 2
 9             ],
10             [
11                 3,
12                 4
13             ],
14             5,
15             [
16                 6,
17                 7
18             ]
19         ],
20         "para": 1.2
21     },
22     "4": {
23         "id": 4,
24         "name": "",
25         "desc": {
26             "id": 5,
27             "num": [
28                 1
29             ]
30         },
31         "para": 3.45
32     },
33     "6": {
34         "id": 6,
35         "name": "",
36         "desc": [
37             {
38                 "a": 10
39             }
40         ],
41         "para": 6.0
42     }
43 }

 

posted on 2019-08-04 21:54  艰苦奋斗中  阅读(687)  评论(0编辑  收藏  举报