前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python从mysql导出数据导excel

python从mysql导出数据导excel

作者头像
IT架构圈
发布2018-06-01 11:02:33
3.4K0
发布2018-06-01 11:02:33
举报
文章被收录于专栏:IT架构圈IT架构圈
代码语言:javascript
复制
# 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')
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-03-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程坑太多 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档