需求:
因需要将一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 += 1 elif key == "LEN": worksheet.write(val2, 1, value) val2 += 1 elif key == "ID": worksheet.write(val3, 2, value) val3 += 1 elif key == "OTHER": worksheet.write(val4, 3, value) val4 += 1 else: 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