博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python实现读取json文件到excel表
阅读量:4581 次
发布时间:2019-06-09

本文共 949 字,大约阅读时间需要 3 分钟。

一、需求

1、'score.json' 文件内容:

{    "1":["小花",99,100,98.5],    "2":["小王",90,30.5,95],    "3":["小明",67.5,49.6,88]}

 

2、读取json文件保存到数据库,并计算出每个人的总分和平均分

 

二、实现代码

import json, xlwtdef read_score(jsonfile):    with open(jsonfile, encoding='utf-8') as f:  # 将json文件转化为字典        score_all = json.load(f)    book = xlwt.Workbook()  # 创建excel文件    sheet = book.add_sheet('sheet1')  # 创建一个表    title = ['序号', '姓名', '语文', '数学', '英语', '总分', '平均分']    for col in range(len(title)):  # 存入第一行标题        sheet.write(0, col, title[col])    row = 1  # 定义行    for k in score_all:        data = score_all[k]  # data保存姓名和分数的list        data.append(sum(data[1:4]))  # 倒数第二列加入总分        data.append(sum(data[1:4]) / 3.0)  # 最后一列加入平均分        data.insert(0, k)  # 第一列加入序号        for index in range(len(data)):  # 依次写入每一行            sheet.write(row, index, data[index])        row += 1    book.save('score.xls')read_score('score.json')

 

转载于:https://www.cnblogs.com/jessicaxu/p/7855812.html

你可能感兴趣的文章