mysql导出为excel

import pymysql
import xlwt

# excel参数设置
# refer https://blog.51cto.com/u_16213670/10326649


def export_to_excel(worksheet, cursor, table):
    """
    将MySQL一个数据表导出到excel文件的一个表的函数
    :param    worksheet:  准备写入的excel表
    :param    cursor:     源数据的数据库游标
    :param    table       源数据的数据表
    :return:  Nove.
    """
    # 首先向excel表中写入数据表的字段
    column_export = [字段名称]
    for i in range(len(column_export)):
        # 行,列,内容
        worksheet.write(0, i, column_export[i])

    sql = "SELECT  字段名称 FROM 表名称  WHERE video_content_analysis  IS NOT NULL ORDER BY `duration` DESC  LIMIT 10"

    # 向构建好字段的excel表写入所有的数据记录
    row_count = cursor.execute(sql)
    for i in range(row_count):
        temptuple = cursor.fetchone()
        for j in range(len(column_export)):
            worksheet.write(i + 1, j, temptuple[j])


if __name__ == '__main__':

    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet("sheet1")

    connect = pymysql.connect(host='',
                              user='',
                              password='',
                              database='')

    cursor = connect.cursor()

    export_to_excel(worksheet, cursor, 'maincdrs')

    cursor.close()
    connect.close()

    workbook.save("basic_data_maincdrs.xls")

 

posted @ 2024-05-06 11:52  Coding_Yong  阅读(22)  评论(0编辑  收藏  举报