您的位置:首页 > 编程语言 > Python开发

如何利用python从mysql中将数据导出到excel

2017-06-09 16:39 711 查看
一.需求:

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')  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: