mysql 数据转excel文件

mysql 数据转excel文件

缘由

为售后拉取数据,用navicat太墨迹了,用python写一个main方法跑一下;

1.抽取共同方法,封装成传入mysql,直接下载成excel;

2.写入所有sql语句,传入参数;

代码

python 复制代码
'''
@Author: Jeff.zheng
@Date : 2024/4/27
@Desc : mysql 转成excel文件
'''

import json
import os
import time
from datetime import datetime
import pandas as pd
import pymysql.cursors
from future.backports.datetime import timedelta


# 获取游标
def getCursor():
    # 创建连接
    Connection = pymysql.connect(
        host='127.0.0.1',  # 数据库主机地址
        user='root',  # 数据库用户名
        password='123456',  # 数据库密码
        db='cloud3',  # 数据库名
        cursorclass=pymysql.cursors.DictCursor  # 使用DictCursor以字典形式返回查询结果
    )

    cursorOfConnection = Connection.cursor()
    return cursorOfConnection


# 获取结果
def getResultBySql(cursorOfConnection, sql):
    try:
        cursorOfConnection.execute(sql)
        # 获取查询结果
        Result = cursorOfConnection.fetchall()
        return Result
    except Exception as e:
        print(e)
        cursorOfConnection.close()


def exportExcelByList(listData, dateName, fileName):
    df = pd.DataFrame(listData)
    # 设置表头
    need_path = os.path.join(os.path.expanduser("~"), "Desktop") + '/测试文件夹-' + dateName
    os.makedirs(need_path, exist_ok=True)
    fileNamePath = os.path.join(need_path, fileName + '.xlsx')
    df.to_excel(fileNamePath, index=None)
    # 这里可以格式化或者别的,太麻烦暂不处理;


def sqlToExcel(myCursor, sql, dateName, xlsxName):
    print(xlsxName + "-开始-" + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    sqlResultList = getResultBySql(myCursor, sql)
    exportExcelByList(sqlResultList, dateName, xlsxName)
    print(xlsxName + "-结束-" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "\n")


if __name__ == '__main__':
    cursor = getCursor()
    date = "2024-04-28"
    dateAddOne = (datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')

    sql0 = "SELECT col_device_id  as '所有出货的设备ID'  FROM cj_all_bed "
    sqlToExcel(cursor, sql0, date, "0-所有出货的设备ID")

多表最后效果图


相关推荐
珹洺10 分钟前
数据库系统概论(八)SQL单表查询语言超详细讲解(附带例题表格对比带你一步步掌握)
数据库·sql
斌果^O^20 分钟前
mysql常用方法
数据库·mysql
全职计算机毕业设计22 分钟前
SpringBoot Vue MySQL酒店民宿预订系统源码(支付宝沙箱支付)+代码讲解视频
vue.js·spring boot·mysql
man201722 分钟前
基于ssm+mysql的高校设备管理系统(含LW+PPT+源码+系统演示视频+安装说明)
数据库·mysql·ssm
不辉放弃2 小时前
java连数据库
java·mysql
GzlAndy2 小时前
MySQL全局优化
数据库·mysql
m0_741574752 小时前
mysql主从同步
数据库·mysql
小白教程3 小时前
MySQL数据库的安全性防护
数据库·mysql
Lion Long3 小时前
CodeBuddy 中国版 Cursor 实战:Redis+MySQL双引擎驱动〈王者荣耀〉战区排行榜
数据库·redis·mysql·缓存·腾讯云·codebuddy首席试玩官·codebuddy
apcipot_rain6 小时前
【应用密码学】实验五 公钥密码2——ECC
前端·数据库·python