python從mysql導出數據導excel
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