python操作excel及json

有一个存着学生成绩的文件:stuscore.txt,里面存的是json串,json串读起来特别不直观,需要你写代码把它都写到excel中,并计算出总分和平均分,json格式如下:
{
    "1":["小花",99,100,98.5],
    "2":["小王",90,30.5,95],
    "3":["小明",67.5,49.6,88]
}

代码实现如下:

import xlwt,json

res = open('stuscore.txt',encoding='utf-8')
title = ['学号','姓名','语文成绩','数学成绩','英语成绩','总分','平均分']
s_score = json.load(res)
book = xlwt.Workbook()
sheet = book.add_sheet('scoreinfo')

for j in range(len(title)):
    sheet.write(0,j,title[j])

row = 1  #
for i in s_score:
    sheet.write(row, 0, i)  # 第0列写学号
    cl = 1  #
    s = s_score[i]
    sum = s[1] + s[2] + s[3]
    avg = round(sum/3, 2)
    for k in s:
        sheet.write(row,cl,k)
        cl += 1
    sheet.write(row,cl,sum)
    sheet.write(row,cl+1,avg)
    row += 1
book.save('myscore.xls')

 

posted @ 2017-11-16 18:07  真的,秋风来了  阅读(478)  评论(0编辑  收藏  举报