分析接口数据,按照indicator和topic的关联关系写入excel表
写入excel表的类
write_excel.py
import openpyxl
class WriteExcel:
def __init__(self):
self.wbname = './indicator.xlsx'
self.wb = openpyxl.load_workbook(self.wbname) # 打开excel文件
self.sheet = self.wb['IndicatorData'] # 获取工作表
# 写入数据(要关闭excel)
def write_data(self, row, column, indicator_value):
self.sheet.cell(row, column).value = indicator_value
# 写完数据后保存文件
def save_excel(self):
self.wb.save(self.wbname)
实现读数据-分析数据-写数据功能
read_writer_run.py
import json
from test06.test0628.write_excel import WriteExcel
class OperationJson:
def __init__(self):
self.data = self.read_data()
print(len(self.data))
self.all_value = self.all_indicator()
print(self.all_value)
# self.all_value_count = self.all_indicator_count()
# print("指标一共有:{}".format(self.all_value_count)) # 1599个
self.write_excel = WriteExcel()
# 读取json文件 <class 'list'>
def read_data(self):
with open('./data.json', encoding="utf-8") as fp:
data = json.load(fp)
return data
# 获取所有指标的数据 <class 'list'>
def all_indicator(self):
all_value = self.data[1]
return all_value
# 获取单个指标的数据 <class 'dict'>,并且写入excel
def indicator_1(self):
row = 2
for indicator in self.all_value:
# print("指标:", indicator)
indicator_id = indicator['id'] # 写入第1列
print("指标id:", indicator_id)
topics = indicator['topics'] # <class 'list'> topics数据可能为空,也可能是多个值
# print(topics)
if len(topics) == 0:
self.write_excel.write_data(row, 1, indicator_id)
self.write_excel.write_data(row, 2, "None")
row = row + 1
else:
# 获取单个topic数据
for topic in topics:
self.write_excel.write_data(row, 1, indicator_id) # 写入indicator_id
# print("topic", topic)
topic_id = topic['id']
print("topic_id:", topic_id)
self.write_excel.write_data(row, 2, topic_id) # 写入 topic_id
row = row + 1
self.write_excel.save_excel()
if __name__ == '__main__':
j = OperationJson()
j.indicator_1()