数据库
首页 > 数据库> > MYSQL海量数据导出到EXCEL

MYSQL海量数据导出到EXCEL

作者:互联网

import pymysql
import openpyxl
import time
def export_to_excel(worksheet, cursor, table):
    """
    将MySQL一个数据表导出到excel文件的一个表的函数
    :param    worksheet:  准备写入的excel表
    :param    cursor:     源数据的数据库游标
    :param    table       源数据的数据表
    :return:  Nove.
    """
    # 首先向excel表中写入数据表的字段
    column_count = cursor.execute("desc %s"%table)
    for i in range(column_count):
       temptuple = cursor.fetchone()
       #print(temptuple[0])
       worksheet.cell(1, i+1, temptuple[0])

    # 向构建好字段的excel表写入所有的数据记录
    row_count = cursor.execute("select * from %s"%table)
    for i in range(row_count):
        temptuple = cursor.fetchone()
        for j in range(column_count):
            worksheet.cell(i + 1, j+1, temptuple[j])


#workbook = xlwt.Workbook()
workbook = openpyxl.Workbook()
worksheet = workbook.create_sheet("sheet1",0)
localtime = time.localtime(time.time())#获取当前时间
time = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
connect = pymysql.connect(
             user = '',
            password = '',
            db = '',
            host = '',
            port = 3306,
            charset = 'utf8'
            )
cursor = connect.cursor()

export_to_excel(worksheet, cursor, 'xinxi')

cursor.close()
connect.close()

workbook.save(time+".xls")

 

标签:count,海量,excel,MYSQL,EXCEL,cursor,worksheet,time,temptuple
来源: https://www.cnblogs.com/xkdn/p/15479005.html