python操作Excel生成数据库定义的代码

发布时间:2020-09-13编辑:脚本学堂
python操作Excel生成数据库定义的代码

python操作Excel生成数据库定义的代码,有需要的朋友可以参考下。
   

复制代码 代码如下:
#!/usr/bin/env python 
    # -*- coding:utf8  -*- 
    import xlrd  
     
     
    class WorkBook(): 
        def __init__(self): 
            pass 
        def __del__(self): 
            pass 
        def readExcel(self,excelFile): 
            book = xlrd.open_workbook(excelFile) 
            return book 
        def readSheet(self,sheet):         
            lifiled = sheet.col(2)[5:]  #字段 
            litype = sheet.col(4)[5:]   #类型 
            lilength = sheet.col(5)[5:] #长度 
            linull = sheet.col(6)[5:]   #是否为空 
            #print "++++++++++++++++++++++++++++++++++++" 
            
            print "CREATE TABLE DamsDB.dbo.%s" %(sheet.name,) 
         
            print "(" 
            for i in range(0,(sheet.nrows - 5)): 
                if lilength[i].value != "": 
                    if linull[i].value == "": 
                        print "    %s %s (%s)," %(lifiled[i].value,litype[i].value,lilength[i].value) 
                    else: 
                         print "    %s %s (%s) %s," %(lifiled[i].value,litype[i].value,lilength[i].value,"NOT NULL") 
                else: 
                    if linull[i].value != "": 
                        print "    %s %s %s," %(lifiled[i].value,litype[i].value,linull[i].value) 
                    else: 
                         print "    %s %s," %(lifiled[i].value,litype[i].value) 
            print ")" 
            print "GO" 
            print "n" 
            #print "++++++++++++++++++++++++++++++++++++" 
     
     
    if __name__ == "__main__": 
        workbook = WorkBook() 
        book = workbook.readExcel("d:a.xls") 
        print "The number of worksheets is", book.nsheets 
         
        for i in range(3, book.nsheets): 
            #print "+++++++++++ i ==",i 
            workbook.readSheet(book.sheet_by_index(i))