JSON轉EXCEL Python
阿新 • • 發佈:2017-12-21
reload add str turn lis tde def div bsp
具體參數根據實際情況調整
1 # -*- coding: utf-8 -* 2 import json 3 import xlwt 4 import os 5 import sys 6 7 reload(sys) 8 sys.setdefaultencoding(‘utf-8‘) 9 dir = os.getcwd().decode(‘utf-8‘) 10 dirList = os.listdir(dir) 11 print dirList 12 13 14 def readjson(): 15 s = [] 16 for file in dirList:17 if ".json" in file: 18 with open(file, ‘r‘) as fr: # 用with打開文件 19 data = json.load(fr) # 用json中的load方法,將json串轉換成字典 20 s.append(data) # 保存所有字典到列表中 21 return s 22 23 24 def writeExcel(J): 25 workbook = xlwt.Workbook(encoding=‘utf-8‘) 26booksheet = workbook.add_sheet(‘Sheet‘, cell_overwrite_ok=True) 27 rvalue = J 28 # print rvalue 29 title = [] 30 for k, v in enumerate(rvalue[0]): 31 title.append(v) 32 booksheet.write(0, k, v) 33 print title 34 35 for a in range(len(rvalue)): 36 forb in range(len(title)): 37 try: 38 d = title[b] 39 c = str(rvalue[a][d]) 40 # if c: 41 booksheet.write(a + 1, b, c) 42 # else: 43 # if c == ‘‘: 44 # booksheet.write(a + 1, b, ‘{}‘) 45 # else: 46 # booksheet.write(a + 1, b, ‘{}‘) 47 except: 48 booksheet.write(a + 1, b, ‘‘) 49 workbook.save(u‘Merge‘ + ‘.xls‘) 50 51 52 if __name__ == ‘__main__‘: 53 qqq = json.dumps(readjson()[0], encoding="UTF-8", ensure_ascii=False) 54 writeExcel(readjson()[0])
JSON轉EXCEL Python