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

来源:互联网 发布:设计字体的软件 编辑:程序博客网 时间:2024/06/05 09:37
#encoding:utf-8'''Created on 2017年4月12日@author: ***'''import ConfigParser  #读入配置文件import MySQLdb #链接mysqlimport xlwt #Excelconf_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()  #创建一EXCLEsheet=excel.add_sheet('test')  #添加一sheet页名,命名为testtitle = cursor.description  #获取列名#列名写入Excelfor 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()    

0 0
原创粉丝点击