python3實現mysql匯出excel的方法
阿新 • • 發佈:2020-01-09
Mysql中'employee'表內容如下:
# __Desc__ = 從資料庫中匯出資料到excel資料表中 import xlwt import pymysql class MYSQL: def __init__(self): pass def __del__(self): self._cursor.close() self._connect.close() def connectDB(self): """ 連線資料庫 :return: """ try: self._connect = pymysql.Connect( host='localhost',port=3306,user='root',passwd='123456',db='test',charset='utf8' ) return 0 except: return -1 def export(self,table_name,output_path): self._cursor = self._connect.cursor() count = self._cursor.execute('select * from '+table_name) # print(self._cursor.lastrowid) print(count) # 重置遊標的位置 self._cursor.scroll(0,mode='absolute') # 搜取所有結果 results = self._cursor.fetchall() # 獲取MYSQL裡面的資料欄位名稱 fields = self._cursor.description workbook = xlwt.Workbook() # 注意: 在add_sheet時,置引數cell_overwrite_ok=True,可以覆蓋原單元格中資料。 # cell_overwrite_ok預設為False,覆蓋的話,會丟擲異常. sheet = workbook.add_sheet('table_'+table_name,cell_overwrite_ok=True) # 寫上欄位資訊 for field in range(0,len(fields)): sheet.write(0,field,fields[field][0]) # 獲取並寫入資料段資訊 row = 1 col = 0 for row in range(1,len(results)+1): for col in range(0,len(fields)): sheet.write(row,col,u'%s' % results[row-1][col]) workbook.save(output_path) if __name__ == '__main__': mysql = MYSQL() flag = mysql.connectDB() if flag == -1: print('資料庫連線失敗') else: print('資料庫連線成功') mysql.export('employee','E:/test_input.xls')
執行結果如下:
總結
以上所述是小編給大家介紹的python3實現mysql匯出excel的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!