python3實現mysql導出excel
阿新 • • 發佈:2018-05-05
pass path 所有 exp output %s con href details
轉載:tingzuhuitou
# coding:utf8 import sys # __Desc__ = 從數據庫中導出數據到excel數據表中 import xlwt import pymysql def export(host, user, password, dbname, table_name,output_path): conn = pymysql.connect(host, user, password, dbname, charset=‘utf8‘) cursor = conn.cursor() print(cursor.rownumber) count= cursor.execute(‘select * from ‘+table_name) print(cursor.rownumber) print(cursor.lastrowid) print(count) # 重置遊標的位置 cursor.scroll(0,mode=‘absolute‘) print(cursor.rownumber) # 搜取所有結果 results = cursor.fetchall() # 獲取MYSQL裏面的數據字段名稱 fields = cursor.description workbook= xlwt.Workbook() 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__": export(‘localhost‘, ‘root‘, ‘123456‘, ‘test‘, ‘test_input‘, ‘E:/test_input.xls‘)
python3實現mysql導出excel