首页 > 代码库 > python导出数据到excel

python导出数据到excel

#!/usr/bin/env python  
#coding=utf8   
import xlwt  
import MySQLdb 
import datetime
 

host = localhost
user = scott
passwd = oracle
db = mobp2p
port = 3307
unix_socket = /data/mysql3307/tmp/3307.sock
sql_exec_30 = select * from mobp2p.yyd_u_bank limit 3
sql_exec_40 = select * from mobp2p.yyd_u_bank limit 4
sql_exec_fenqi = select * from mobp2p.yyd_u_bank
outputdir = /root/liangguojun/csv.xls

conn=MySQLdb.connect(host,user,passwd,db,port,unix_socket,charset=utf8)   
cursor=conn.cursor()  
wbk = xlwt.Workbook() 
my_style = xlwt.easyxf(num_format_str=YYYY-MM-DD HH:mm:SS) 

def exp_xls (sql_exec,my_sheet,lie):
    count = cursor.execute(sql_exec)       
    cursor.scroll(0,mode=absolute)   
    results = cursor.fetchall()     
    fields = cursor.description       
    sheet = wbk.add_sheet(my_sheet,cell_overwrite_ok=True) 
    for ifs in range(0,len(fields)):  
        sheet.write(0,ifs,fields[ifs][0])          
    ics=1  
    jcs=0     
    for ics in range(1,len(results)+1):  
        for jcs in range(0,len(fields)):  
            sheet.write(ics,jcs,results[ics-1][jcs]) 
             
    for var in range(1,len(results)+1):   
        sheet.write(var,lie,results[var-1][lie],my_style)             
               
               
exp_xls(sql_exec_30,30,4)
exp_xls(sql_exec_40,40,3)
exp_xls(sql_exec_fenqi,fenqi,3)                           

                      
wbk.save(outputdir)  
   

    

 

python导出数据到excel