python3学习笔记之五——将json数据写入excel表

#student4.json

[
    {
        "student_no": 1001,
        "name": "James",
        "score": 10,
        "class": "A-1",
        "rank": 1
    },
    {
        "student_no": 1002,
        "name": "Tome",
        "score": 91,
        "class": "A-1",
        "rank": 2
    },
    {
        "student_no": 1003,
        "name": "Jane",
        "score": 100,
        "class": "A-3",
        "rank": 3
    },
    {
        "student_no": 1004,
        "name": "Rone",
        "score": 50,
        "class": "A-3",
        "rank": 4
    },
    {
        "student_no": 1005,
        "name": "Bill",
        "score": 44,
        "class": "A-3",
        "rank": 5
    },
    {
        "student_no": 1006,
        "name": "Lily",
        "score": 81,
        "class": "A-2",
        "rank": 6
    }

]

利用json.load(),将json数据转化成数组,数组中的每一项都是字典。

jsonfile = json.load(open(r'd:\student4.json'))

得到数组:

[{'student_no': 1001, 'name': 'James', 'score': 10, 'class': 'A-1', 'rank': 1}, {'student_no': 1002, 'name': 'Tome', 'score': 91, 'class': 'A-1', 'rank': 2}, {'student_no': 1003, 'name': 'Jane', 'score': 100, 'class': 'A-3', 'rank': 3}, {'student_no': 1004, 'name': 'Rone', 'score': 50, 'class': 'A-3', 'rank': 4}, {'student_no': 1005, 'name': 'Bill', 'score': 44, 'class': 'A-3', 'rank': 5}, {'student_no': 1006, 'name': 'Lily', 'score': 81, 'class': 'A-2', 'rank': 6}]

其中student_no,name,score,class,rank这几个键值要作为excel的表头写入表格。

写入表格之前先要了解下如何向excel写入数据,这里就要引入xlwt模块

    workbook = xlwt.Workbook()

    sheet1 = workbook.add_sheet('student')

sheet1.write('行号’,'列号',‘值’)#向excel中写入数据

数据添加完成后,只需保存为文件就可以写入:

workbook.save('student.xls')

接下来先将表头写入表格

ll = list(jsonfile[0].keys) #获取健值,将其转化为list

通过for循环,就可以将ll中的数据写入excel表作为表头。

for i in range(0,len(ll)):

    sheet1.write(0,i,ll[i])

同理将学生数据写入即可。

完整代码 如下:

import xlwt,json

def readJsonfile ():
jsobj = json.load( open ( r 'C: \U sers \C ryptFiend\Downloads \p ython\student4.json' ))
return jsobj

def jsonToexcel ():
jsonfile = readJsonfile()
print (jsonfile)
workbook = xlwt.Workbook()
sheet1 = workbook.add_sheet( 'student' )
ll = list (jsonfile[ 0 ].keys())
for i in range ( 0 , len (ll)):
sheet1.write( 0 ,i,ll[i])
for j in range ( 0 , len (jsonfile)):
m = 0
ls = list (jsonfile[j].values())
for k in ls:
sheet1.write(j + 1 ,m,k)
m += 1
workbook.save( 'student3.xls' )
jsonToexcel()


执行结果如下:

python3学习笔记之五——将json数据写入excel表_第1张图片








你可能感兴趣的:(python3)