python从mysql导出大量数据_python从mysql导出数据导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')

本文分享自微信公众号 - 编程坑太多(idig88),作者:看更多☞

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2018-03-14

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值