通过配置文件连接数据库查询并写入Excel

    xiaoxiao2021-04-13  28

    #encoding:utf-8 ''' Created on 2017年4月12日 @author: *** ''' import ConfigParser #读入配置文件 import MySQLdb #链接mysql import xlwt #Excel conf_path='F:\\PROJECT\\python\\code\\Study_1\\src\\20170412\\conf.ini' config = ConfigParser.ConfigParser() ##读配置文件 config.read(conf_path) #读配置文件 mysql_host = config.get("data","host") mysql_port = int(config.get("data","port")) mysql_user = config.get("data","user"); mysql_passwd = config.get("data","passwd") mysql_db = config.get("data","db") #conf.init 数据库链接配置文件示例 ''' [data] host=*** port=*** ... ''' db = MySQLdb.connect(host = mysql_host, port =mysql_port, user = mysql_user, passwd = mysql_passwd, db = mysql_db, charset='utf8') #链接数据库 sql='SELECT * FROM `t_bi_brand_ad_activity_mapping' cursor = db.cursor() cursor.execute(sql) result = cursor.fetchall() excel= xlwt.Workbook() #创建一EXCLE sheet=excel.add_sheet('test') #添加一sheet页名,命名为test title = cursor.description #获取列名 #列名写入Excel for i in range(0,len(title)): sheet.write(0,i,title[i][0]) #获取数据 for i in range(1,len(result)+1): for j in range(0,len(title)): sheet.write(i,j,result[i-1][j]) #result[i-1]获取数据需要从0开始获取,但是写入数据是总行1开始写 excel.save('a4.xls') db.close()
    转载请注明原文地址: https://ju.6miu.com/read-668708.html

    最新回复(0)