需求:在网上爬取了一些食物的含量信息,每一个食品一个文件,文件内容为json格式,需要将这些食品信息汇总到一个excel中,如下图
```
代码块放到这里
```
代码块放到这里
代码块放到这里
import xlrd
import json
import os
from openpyxlimport Workbook
wb= Workbook()
ws= wb.active
cols= []
def json2excel(jsfile, excfile):
# 读取json数据
a=1
if os.path.exists(jsfile):
# 先用key值写表头
# print("11111111111111111")
with open(jsfile, 'r', encoding='utf8')as fp:
# 先用key值写表头
line= fp.readline()
if not line:
print("没有内容")
else:
# 每一行转换成字典类型
jsdata= json.loads(line)
# 用key值做标题
# print("+++++++++++++++++++++++++++++"+str(cols))
# print(type(cols))
# print(cols is None)
# print(len(cols))
if len(cols)== 0 :
cols.append("code")
cols.append("name")
for kin jsdata.keys():
if k=="ingredient":
print("进入key读取")
ingredient= jsdata.get("ingredient")
# print(ingredient.keys())
for cin ingredient.keys():
# print("==22==2=222----------------"+c)
cols.append(c)
# cols.append("name")
ws.append(cols)# 标题
# print("cols======"+str(cols))
# print()
# 写值
with open(jsfile, 'r', encoding='utf8')as fp:
# 循环写值
while True:
print('正在写入的行数%s:' % a)
line= fp.readline()
# print(line)
if not line:
break
# 转换为python对象
jsdata= json.loads(line)
rowdata= []
rowdata.append(jsdata.get("code"))
rowdata.append(jsdata.get("name"))
for colin cols:
# 获取每一行key值对应的value值
ingredient= jsdata.get("ingredient")
# print("=="+str(ingredient))
if ingredient.get(col)is not None:
rowdata.append(ingredient.get(col))
# print("value===="+str(ingredient.get(col)))
# rowdata.append(jsdata.get("name"))
# rowdata.append(jsdata.get("code"))
# print(jsdata.get("name"))
# print("-------------------"+str(rowdata))
a+= 1
ws.append(rowdata)# 写行
# ws.append(cols) # 标题
print('保存中')
wb.save(excfile)# 保存
if __name__== '__main__':
s= 1
# path = "D:/PycharmProjects/jsonExcel/date/"
path= "E:/work/data2/"
files= os.listdir(path)
for fin files:
filelist= os.path.isfile(path+ '/' + f)
# print(f)
filepath= path+ f
print(filepath)
# excfile = "./222-1.xlsx"
excfile= "./333.xlsx"
json2excel(filepath, excfile)
# jsfile = "./_AGIAaqianyachunganlanyou.json"
# excfile = "./111.xlsx"
# json2excel(jsfile, excfile)