如何利用python從mysql中將數據導出到excel

一.需求:
1. 需要寫個python程序,把config 庫的tag表的2016-7-29 19:47 (create_time) 之前創建的10.1 版本(mysql_version=9)的實例導出到文本文件中,導出字段包括 id,ip,belong_app,app 
描述(與 resources_app 表關聯,取name 字段).
2. 上述導出內容,生成excel

二.編寫腳本如下:
sys.setdefaultencoding('utf8')
    # __author__ = 'zxw'
    # __date__ = '2017/4/13'
    # __Desc__ = 從數據庫中導出數據到excel數據表中
    
import xlwt
import MySQLdb
    
def export(host,user,password,dbname,outputpath):        
        conn = MySQLdb.connect(host,user,password,dbname,charset='utf8')
        cursor = conn.cursor()
        sql = "select tag.id,tag.ip,tag.belong_app,app.name,tag.mysql_version from tag join resources_app app on tag.belong_app=app.id where tag.create_time <\'2016-7
-29 19:47\' and tag.mysql_version=8"
        count = cursor.execute(sql)
        print count
        # 重置遊標的位置
        cursor.scroll(0,mode='absolute')
        # 搜取所有結果

        results = cursor.fetchall()    

        # 獲取MYSQL裏面的數據字段名稱
        fields = cursor.description
        workbook = xlwt.Workbook()
        sheet = workbook.add_sheet('test',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(outputpath)    
    
    # 結果測試
if __name__ == '__main__':
        export('IP','用戶名','密碼','config','datetest.xls')  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章