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的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
