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

執行結果如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM