Python学习打卡--day45(练习:分析数据并且写入excel表)

分析接口数据,按照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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值