Python 實現MySQL數據導入Excel

一、場景

場景如題,將mysql中的表數據導入到excel


二、場景實現

1、創建mysql_util.py

將對mysql的操作寫在這個py文件下

mysql_conf = {
    'host': '主機host',
    'user': '用戶名',
    'password': '密碼',
    'port': 端口,
    'database': '庫名',
    'charset': 'utf8'
}

class MySQLUtil:
    def __init__(self, conf):
        logging.basicConfig(level=logging.DEBUG,
                            format='[%(asctime)s] %(levelname)s [%(funcName)s: %(filename)s, %(lineno)d] %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S')
        self.conn = pymysql.connect(**conf)
        self.cursor = self.conn.cursor()

    # 獲取遊標
    def get_cur(self):
        return self.cursor

    # 事務提交
    def commit(self):
        self.conn.commit()

    # 關閉連接
    def close(self):
        self.conn.close()

    #關閉遊標
    def curclose(self):
        self.cursor.close()

    # 回滾事務
    def rollback(self):
        self.conn.rollback()
    '''
        數據導入excel的查詢操作
    '''
    def queryOperationExcel(self,sql,flag):
        # 獲取數據庫遊標
        cur = self.get_cur()
        # 執行查詢
        try:
            cur.execute(sql)
            #移動遊標位置
            cur.scroll(0,mode="absolute")
            # 查詢結果條數
            # row = cur.rowcount
            # 查詢結果集
            #flag等於1:查詢結果集
            #flag等於2:查詢表結構描述
            if flag==1:
                dataList = cur.fetchall()
            elif flag==0:
                dataList = cur.description
        except Exception as e:
            logging.error('查詢結果集異常{0}'.format(e))
        # 關閉遊標
        # cur.close()
        # 關閉數據連接
        # self.close()
        # 返回查詢結果集
        logging.info('{}'.format(dataList))
        return dataList
    '''
    查詢mysql數據 將mysql表數據導入到excel
    '''
    def getmysqldata(self,tablename,flag):
        sql = "SELECT * FROM {0}".format(tablename)
        try:
            logging.info('{}'.format(sql))
            data = self.queryOperationExcel(sql,flag)
        except Exception as e:
            logging.error('{}'.format(e))
        else:
            logging.info('獲取excel數據成功:{}'.format(data))
            return data

2、創建excelutils.py

實現具體導入excel邏輯

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : linjie
# @Des     : py將MySQL數據導出到excel
import logging
import mysql_util as mysql_util
import xlwt
from util import mysql_util
from util.mysql_util import MySQLUtil
class ExcelUtils:
# 日誌配置
    logging.basicConfig(level=logging.DEBUG,
                        format='[%(asctime)s] %(levelname)s [%(funcName)s: %(filename)s, %(lineno)d] %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    '''
    mysql數據導入excel
    sheet_name:excel excel名稱
    dbname:數據庫名
    tablename:表名
    out_path:文件存放路徑
    flag1:數據表結果集查詢標誌
    flag2:數據表描述查詢標誌
    '''
    def mysql_to_excel(self,sheet_name,tablename,out_path,flag1=1,flag2=0):
        mysqldb = MySQLUtil(mysql_util.mysql_conf)
        #結果集
        datalist = mysqldb.getmysqldata(tablename,flag1)
        logging.info('結果集:{}'.format(datalist))
        #表描述
        tabledesc = mysqldb.getmysqldata(tablename,flag2)
        logging.info('表描述:{}'.format(tabledesc))
        #創建excel
        workbook = xlwt.Workbook()
        #創建excel中的sheet
        sheet = workbook.add_sheet(sheet_name,cell_overwrite_ok=True)
        
        #插入表描述到excel
        for desc in range(0,len(tabledesc)):
            sheet.write(0,desc,tabledesc[desc][0])
        row = 1
        col = 0
        #插入數據到excel
        for row in range(1,len(datalist)+1):
            for col in range(0,len(tabledesc)):
                sheet.write(row,col,u'%s'%datalist[row-1][col])
        try:
            #保存excel
            workbook.save(out_path)
        except Exception as e:
            logging.error('導出數據到excel失敗:{}'.format(e))
        else:
            logging.info('導出成功')
            #數據庫連接關閉二連
            mysqldb.curclose()
            mysqldb.close()

if __name__ == '__main__':
    mysql_excel = ExcelUtils()
    mysql_excel.mysql_to_excel('build','ms_commsum','test.xls')

ok,數據即可導入到excel中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章