涉及到的相關庫:
pymysql、
xlwt
庫函數(將MySQL一個數據表導出到excel文件的一個表)
文件exportexcel.py內容:
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() worksheet.write(0, i, 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.write(i + 1, j, temptuple[j])
測試過程:
1.准備內容
在MySQL數據庫中創建一個導出到excel的數據表,並插入一定的數據記錄。如圖在遠程MySQL服務器(192.168.0.102)上,創建了一個數據庫chapter04和數據表student。
2.測試樣例
在example.py文件中調用函數export_to_excel,測試效果
文件example.py內容:
import pymysql import xlwt from exportexcel import export_to_excel workbook = xlwt.Workbook() worksheet = workbook.add_sheet("sheet1") connect = pymysql.Connect( host='192.168.0.102', port=3306, user='root', passwd='12345678', db='chapter04' ) cursor = connect.cursor() export_to_excel(worksheet, cursor, 'student') cursor.close() connect.close() workbook.save("student grade.xls")
3. 執行效果