一、需求
1、'score.json' 文件內容:
{
"1":["小花",99,100,98.5],
"2":["小王",90,30.5,95],
"3":["小明",67.5,49.6,88]
}
2、讀取json文件保存到數據庫,並計算出每個人的總分和平均分
二、實現代碼
import json, xlwt def 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')