需求:
因需要將一json文件中大量的信息填入一固定格式的Excel表格,單純的復制粘貼肯定也能完成,但是想偷懶一下,于是借助Python解決問題。
環境:
Windows7 +Python2.7 +Xlwt
具體分析:
原始文件為json列表,列表中有多個字典,生成Excel文件需要將列表中的字典的鍵值按鍵對應排列,也就是說,所有為“XX”的鍵對應的值寫在一列,且每個字典中的不同鍵的鍵值保證在同一行。?
解決思路是,讀取json文件,然后遍歷字典的鍵和值,讀完第一個字典并寫入Excel后換行,讀取第二個字典。
代碼:
# -*- coding: utf-8 -*- import xlwt import json# 創建excel工作表 workbook = xlwt.Workbook(encoding='utf-8') worksheet = workbook.add_sheet('sheet1')# 設置表頭 worksheet.write(0, 0, label='NAME') worksheet.write(0, 1, label='LEN') worksheet.write(0, 2, label='ID') worksheet.write(0, 3, label='OTHER')# 讀取json文件 with open('test.json', 'r') as f:data = json.load(f)# 將json字典寫入excel # 變量用來循環時控制寫入單元格,感覺有更好的表達方式 val1 = 1 val2 = 1 val3 = 1 val4 = 1 for list_item in data:for key, value in list_item.items():if key == "NAME":worksheet.write(val1, 0, value)val1 += 1elif key == "LEN":worksheet.write(val2, 1, value)val2 += 1elif key == "ID":worksheet.write(val3, 2, value)val3 += 1elif key == "OTHER":worksheet.write(val4, 3, value)val4 += 1else:pass# 保存 workbook.save('OK.xls')
輔助文件:
test.json[{"OTHER": "code","NAME": "whc","LEN": 100,"ID": "01-0001"},{"OTHER": "house","NAME": "ikd","LEN": 200,"ID": "01-0002"},{"OTHER": "thank","NAME": "qxf","LEN": 300,"ID": "01-0003"},{"OTHER": "music","NAME": "kmn","LEN": 400,"ID": "01-0004"},{"OTHER": "big","NAME": "vbf","LEN": 500,"ID": "01-0005"},{"OTHER": "over","NAME": "wsr","LEN": 600,"ID": "01-0006"} ]
結果示例:
ok.xls
?
以上內容來源于 https://www.jb51.net/article/132034.htm