利用python将MySQL数据导出到excel中
涉及到的相关库:
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. 执行效果


浙公网安备 33010602011771号