python数据库导出为excel(python处理json字符串)

'''
@Author: Jeff.zheng
@Date : 2024/4/22
@Desc :  python数据库导出为excel
'''

# 导入PyMySQL库
import json
import time

import pandas as pd
import pymysql.cursors

if __name__ == '__main__':

    list = []

    # 创建连接
    connection = pymysql.connect(
        host='localhost',  # 数据库主机地址
        user='root',  # 数据库用户名
        password='123456',  # 数据库密码
        db='softide_cloud3',  # 数据库名
        cursorclass=pymysql.cursors.DictCursor  # 使用DictCursor以字典形式返回查询结果
    )

    try:
        with connection.cursor() as cursor:
            # 编写SQL查询语句
            sql_query = "SELECT DISTINCT a.id,a.col_user_id,a.col_date,a.col_device_id,a.col_phone ,b.col_diary,b.create_date FROM day_idea  a LEFT JOIN tb_sleep_diary b on a.id = b.id "

            # 执行查询
            cursor.execute(sql_query)

            # 获取查询结果
            result = cursor.fetchall()

            for row in result:
                try:
                    temp = {}
                    temp = json.loads(row['col_diary'])

                    temp['before_sleeping_habits'] = str(temp['before_sleeping_habits']).replace("sport", "运动") \
                        .replace(
                        "drink_wine", "饮酒").replace("drink_coffee", "喝咖啡").replace("take_medicine", "吃药").replace(
                        "midnight_snack", "宵夜").replace("game", "游戏").replace("other", "其他")

                    temp['sleeping_status'] = str(temp['sleeping_status']).replace("best", "非常好").replace("better",
                                                                                                          "良好").replace(
                        "good", "一般").replace("bad", "很差").replace("worse", "非常差")

                    temp['body_status'] = str(temp['body_status']).replace("fitness", "正常").replace("sleeplessness",
                                                                                                    "失眠").replace(
                        "catch_a_code", "感冒").replace("ffever", "发烧").replace("chest_distress", "胸闷").replace(
                        "flustered", "(心慌").replace("fatigue", "疲惫").replace("menstrual_period", "经期").replace(
                        "climacterium", "更年期").replace("other", "其他").replace("stress_big", "压力大")
                    # 移除多余元素
                    del row['col_diary']
                    merged_dict = {**row, **temp}  # 扩展运算
                    list.append(merged_dict)
                except Exception as e:
                    print("===============>" + str(e))
                    pass

            df = pd.DataFrame(list)
            # 设置表头
            header_rename_dict = {'id': '编号', 'col_user_id': '用户编号', 'col_date': '日期', 'col_device_id': '设备号',
                                  'col_phone': '电话', 'before_sleeping_habits': '睡前行为',
                                  'before_sleeping_habits_other': '其他睡前行为', 'body_status': '身体状态',
                                  'body_status_other': '其他身体状态', 'sleeping_status': '睡眠状态',
                                  'create_date': '创建时间'}
            df = df.rename(columns=header_rename_dict)
            fileName = '睡眠日记' + str(int(time.time())) + '.xlsx'
            df.to_excel(fileName, index=False)
    finally:
        # 关闭连接
        connection.close()

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值