json数据为字典类型,一行一个字典
代码如下:
import xlwt
import json
# 创建excel工作表
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('sheet1')
# 设置表头
worksheet.write(0, 0, label='商品名')
worksheet.write(0, 1, label='申请号')
worksheet.write(0, 2, label='产品号')
worksheet.write(0, 3, label='申请类型')
worksheet.write(0, 4, label='活性成分')
worksheet.write(0, 5, label='剂型/给药途径')
worksheet.write(0, 6, label='规格/剂量')
worksheet.write(0, 7, label='RLD')
worksheet.write(0, 8, label='RS')
worksheet.write(0, 9, label='申请号原始批准/暂定批准日期')
worksheet.write(0, 10, label='产品号批准日期')
worksheet.write(0, 11, label='申请人')
worksheet.write(0, 12, label='市场状态')
# 读取json文件
with open('FDA_drug_data.json', 'r', encoding="utf-8") as f:
data = f.readlines()
d_p = []
#把json串转成字典放到列表中
for d in data:
ite = json.loads(d)
d_p.append(ite)
#处理异常值
for d in d_p:
d.setdefault("RS", "")
d.setdefault("申请号原始批准/暂定批准日期", "")
d.setdefault("产品号批准日期", "")
d.setdefault("市场状态", "")
d.setdefault("申请人", "")
# 将json字典写入excel
# 变量用来循环时控制写入单元格
val = 1
for dict_p in d_p:
worksheet.write(val, 0, dict_p["商品名"])
worksheet.write(val, 1, dict_p["申请号"])
worksheet.write(val, 2, dict_p["产品号"])
worksheet.write(val, 3, dict_p["申请类型"])
worksheet.write(val, 4, dict_p["活性成分"])
worksheet.write(val, 5, dict_p["剂型/给药途径"])
worksheet.write(val, 6, dict_p["规格/剂量"])
worksheet.write(val, 7, dict_p["RLD"])
worksheet.write(val, 8, dict_p["RS"])
worksheet.write(val, 9, dict_p["申请号原始批准/暂定批准日期"])
worksheet.write(val, 10, dict_p["产品号批准日期"])
worksheet.write(val, 11, dict_p["申请人"])
worksheet.write(val, 12, dict_p["市场状态"])
val += 1
# 保存到本地
workbook.save('FDA_drug_data.xls')
转换后数据如下: