python 조작 EXCEL의 조작 실례 원본 코드(데이터 읽기, 쓰기)

5330 단어 python 스크립트
EXCEL 읽기 작업: excel 데이터를 사전 형식으로 저장
#coding=utf8

# excel 
import xlrd
class GenExceptData(object):
    def __init__(self):
        try:
            self.dataDic={}
            # 
            self.wkbook= xlrd.open_workbook("Requirement.xls")
            # “requirement”
            self.dataSheet=self.wkbook.sheet_by_name("requirement")
            #   excel 
            self.readDataToDicl()
            # 
        except Exception,e:
            print "Read Excel  error:",e
  
    def readDataToDicl(self):
        try:
            nrows = self.dataSheet.nrows
            ncols = self.dataSheet.ncols
           
            print ncols ,nrows
            try:
                for rowNum in  range(1,nrows):       
                            # 
                            # if 
                            try:
                                
                                singleJson={}
                                propertyName=self.dataSheet.cell(rowNum,3).value
                                propertyValue=self.dataSheet.cell(rowNum,4).value
                                                        
                                if self.dataSheet.cell(rowNum,0).value and self.dataSheet.cell(rowNum,2).value:
                                    mdEvent=self.dataSheet.cell(rowNum,0).value
                                    singleJson["serviceId"]=self.dataSheet.cell(rowNum,2).value
                                singleJson[propertyName]=propertyValue                             
                                print singleJson
                                self.dataDic[mdEvent]=singleJson
                                singleJson.clear()
                                
                                
                            except Exception,e:
                                print "Get Data Error:",e
            except Exception,e:
                print "Reading Data Error:",e
        except Exception,e:
            print "Reading Data TO Dic Error:",e

    
                  
        
def test():
    GenExceptData()
    
if __name__=="__main__":
    test()
                   

EXCEL 쓰기: csv 파일의 데이터를 필요에 따라 excel 파일에 쓰기
#coding=utf8

from readCSV import readCSV
import xlwt

class GenTestCase():
    def __init__(self,path="E:\\PythonDemo\\OperExcel\\Demo.csv"):
        self.dataInfor=readCSV(path)
        # 
        self.wkbook=xlwt.Workbook()
        # :“ ”
        self.dataSheet=self.wkbook.add_sheet("shellt")
        self.creatHead()
        
    def creatHead(self):
        firstLine=[]
        # 
        for index in range(len(firstLine)):
            self.dataSheet.write(0,index,firstLine[index])
            
        dataBody=self.dataInfor.buffer
        print dataBody.__len__()
        currentrow=1
        for rowNum in  range(1,len(dataBody)):
            for index in range(len(dataBody[rowNum])):
                if rowNum>1:
                    if dataBody[rowNum-1][0]!=dataBody[rowNum][0] :
                        print currentrow,rowNum
                        if currentrow==1:
                            for cols in range(3):
                                cellValue=dataBody[currentrow][cols]
                                cellValue=cellValue.decode("gbk")
                                data=u"%s"  %(cellValue)
                                self.dataSheet.write_merge(currentrow,rowNum-1,cols,cols,data)
                                
                            for cols in range(6,13):
                                cellValue=dataBody[currentrow][cols]
                                cellValue=cellValue.decode("gbk")
                                data=u"%s"  %(cellValue)
                                self.dataSheet.write_merge(currentrow,rowNum-1,cols,cols,data)      
                        else:   
                            for cols in range(3):
                                cellValue=dataBody[currentrow][cols]
                                cellValue=cellValue.decode("gbk")
                                data=u"%s"  %(cellValue)
                                self.dataSheet.write_merge(currentrow-1,rowNum-1,cols,cols,data)
                            for cols in range(6,12):
                                cellValue=dataBody[currentrow][cols]
                                cellValue=cellValue.decode("gbk")
                                data=u"%s"  %(cellValue)
                                self.dataSheet.write_merge(currentrow-1,rowNum-1,cols,cols,data)                                           
                        currentrow=rowNum+1                         
                    break
            
            for cols in range(3,6):              
                cellValue=dataBody[rowNum][cols]
                cellValue=cellValue.decode("gbk")
                data=u"%s"  %(cellValue)
                self.dataSheet.write(rowNum,cols,data)
                               
        self.wkbook.save(r'reqq.xlsx')
    
                  
        
def test():
    GenTestCase()
    
if __name__=="__main__":
    test()
            
        
            
        

좋은 웹페이지 즐겨찾기