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,jsondefreadJsonfile(): jsobj = json.load(open(r'C:\Users\CryptFiend\Downloads\python\student4.json'))return jsobj
defjsonToexcel(): jsonfile = readJsonfile()print (jsonfile) workbook = xlwt.Workbook() sheet1 = workbook.add_sheet('student') ll =list(jsonfile[0].keys())for i inrange(0,len(ll)): sheet1.write(0,i,ll[i])for j inrange(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()
執行結果如下: