1. 程式人生 > >通過配置檔案連線資料庫查詢並寫入Excel

通過配置檔案連線資料庫查詢並寫入Excel

#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()