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")

多表最后效果图


相关推荐
深度学习04071 小时前
MySQL InnoDB Cluster 部署完整文档
android·mysql·adb
code_slave(码畜)1 小时前
微服务架构落地:分库分表实战(下) —— 分布式主键、跨分片查询与分页聚合防坑
数据库·spring boot·分布式·spring cloud·微服务·架构·分库分表
dishugj1 小时前
https://blog.csdn.net/dishugj/article/details/162068579
数据库·系统架构
时间售卖铺2 小时前
MySQL 安装部署
运维·数据库·mysql·云原生
泡海椒2 小时前
JQuick-SQL 子查询:WHERE、SELECT、HAVING 与派生表实践
数据库·sql
用户0510122572962 小时前
SQLite 学习博客(一):从零建库,理解 SQLite 的角色与第一张表
数据库·sqlite
福娃筱欢2 小时前
金仓数据库配置SSL双向认证
数据库·网络协议·ssl
captain3762 小时前
MyBatis操作数据库(入门1)
数据库·oracle·mybatis
snpgroupcn2 小时前
SAP 系统退役的归档架构怎么设计:可检索、可理解、可追溯、可证明
java·数据库·架构
清水白石0082 小时前
React Native与Flutter长期维护成本对比
开发语言·数据库