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

 

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