python從mysql匯出資料導excel

來源:互聯網
上載者:User

標籤:python excel 匯出

# coding:utf8

import sys

 

reload(sys)

sys.setdefaultencoding('utf8')

# author: 'zkx'

# date: '2018/3/11'

# Desc:從資料庫中匯出資料到excel資料表中

#已封裝,可以直接使用,只需更改sql語句即可

 

import xlwt

import MySQLdb

def export(host,user,password,dbname,table_name,outputpath):

conn = MySQLdb.connect(host,user,password,dbname,charset='utf8')

cursor = conn.cursor()

        #時間戳記相減,轉換為時分秒    匯出到excel時間格式要統一("%Y-%m-%d %H:%i:%S"),不然匯出到excel為null

#concat(floor((lasto/1000-first/1000)/3600),"小時",floor(mod((last/1000-first/1000),3600)/60),"分鐘",round(mod(mod((last/1000-first/1000),3600),60)),"秒")

count = cursor.execute('select node,nodealias,alertgroup,FROM_UNIXTIME(firstoccurrence/1000,"%Y-%m-%d %H:%i:%S") zuizao,FROM_UNIXTIME(lastoccurrence/1000,"%Y-%m-%d %H:%i:%S")zuiwan,(lastoccurrence/1000-firstoccurrence/1000) shijiancha from '+table_name+' where alertgroup="OIDTableMonitor-mdTemp" and  DATE_SUB(CURDATE(),INTERVAL 7 DAY) <=DATE(FROM_UNIXTIME(firstoccurrence/1000,"%Y-%m-%d %H:%i:%S"))')

print count

# 重設遊標的位置

cursor.scroll(0,mode='absolute')

# 搜取所有結果

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(outputpath)

 

 

# 測試

if __name__ == "__main__":

#mysql-ip,使用者,密碼,要執行庫,要查詢表,存放路徑

export('12.16.15.14','eccom','eco','nete','ftnt',r'/opt/datest.xls')



python從mysql匯出資料導excel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.