python3实现mysql导出excel

 Mysql中'employee'表内容如下:

 1 # __Desc__ = 从数据库中导出数据到excel数据表中
 2 import xlwt
 3 import pymysql
 4 
 5 
 6 class MYSQL:
 7     def __init__(self):
 8         pass
 9 
10     def __del__(self):
11         self._cursor.close()
12         self._connect.close()
13 
14     def connectDB(self):
15         """
16         连接数据库
17         :return:
18         """
19         try:
20             self._connect = pymysql.Connect(
21                 host='localhost',
22                 port=3306,
23                 user='root',
24                 passwd='123456',
25                 db='test',
26                 charset='utf8'
27             )
28 
29             return 0
30         except:
31             return -1
32 
33     def export(self, table_name, output_path):
34         self._cursor = self._connect.cursor()
35         count = self._cursor.execute('select * from '+table_name)
36         # print(self._cursor.lastrowid)
37         print(count)
38         # 重置游标的位置
39         self._cursor.scroll(0, mode='absolute')
40         # 搜取所有结果
41         results = self._cursor.fetchall()
42 
43         # 获取MYSQL里面的数据字段名称
44         fields = self._cursor.description
45         workbook = xlwt.Workbook()
46 
47         # 注意: 在add_sheet时, 置参数cell_overwrite_ok=True, 可以覆盖原单元格中数据。
48         # cell_overwrite_ok默认为False, 覆盖的话, 会抛出异常.
49         sheet = workbook.add_sheet('table_'+table_name, cell_overwrite_ok=True)
50 
51         # 写上字段信息
52         for field in range(0, len(fields)):
53             sheet.write(0, field, fields[field][0])
54 
55         # 获取并写入数据段信息
56         row = 1
57         col = 0
58         for row in range(1,len(results)+1):
59             for col in range(0, len(fields)):
60                 sheet.write(row, col, u'%s' % results[row-1][col])
61 
62         workbook.save(output_path)
63 
64 
65 if __name__ == '__main__':
66     mysql = MYSQL()
67     flag = mysql.connectDB()
68     if flag == -1:
69         print('数据库连接失败')
70     else:
71         print('数据库连接成功')
72         mysql.export('employee', 'E:/test_input.xls')

执行结果如下:

原文地址:https://www.cnblogs.com/fuqia/p/8993843.html