python 数据库导出excle 分sheet

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import xlwt
import MySQLdb
def export(host,user,password,dbname,table_name,outputpath):
    conn = MySQLdb.connect(host=host,port=3307,user=user,passwd=password,db=dbname,charset='utf8')
    cursor = conn.cursor()


    count = cursor.execute("select distinct SNAME from "+table_name+"")
    cursor.scroll(0,mode='absolute')
    resultsSNAME =cursor.fetchall()


    workbook = xlwt.Workbook()
    for sname in resultsSNAME:
        sql="select * from "+table_name+" where SNAME='%s' order by TIME desc" % (sname[0])
        print sql
        cursor.execute(sql)
        results = cursor.fetchall()
        fields = cursor.description
        
        for s in range(0,len(results)/65535+1):
            print s
            sheet = workbook.add_sheet(sname[0] ,cell_overwrite_ok=True)
            for field in range(0,len(fields)):
               sheet.write(0,field,fields[field][0])
            row = 1
            col = 0
            if s                 for row in range(1,65535):
                    for col in range(0,len(fields)):
                        sheet.write(row,col,u'%s'%results[65534*s+row-1][col])
            else :
                for row in range(1,len(results)%65534+1):
                    for col in range(0,len(fields)):
                        sheet.write(row,col,u'%s'%results[65534*s+row-1][col])
    workbook.save(outputpath)


        


if __name__ == "__main__":
    export('host','user','passwordl','dbname','file.xlsx')
    print "over"

你可能感兴趣的:(代码片段)