Python對excel寫入資料操作例項程式碼(只供參考)
阿新 • • 發佈:2019-01-27
#coding=utf8 ''' 把buffer中的資訊,寫入到excel中。 並按照要求,構造表格樣式 ''' #匯入readCSV模組,用來獲取buffer資料 from readCSV import readCSV from readConfig import Config #匯入寫excel的操作庫 import xlwt class GenTestCase(object): def __init__(self,configObj=Config()): try: #建立一個readCSV物件 self.dataInfor=readCSV(configObj) #建立工作薄 self.wkbook=xlwt.Workbook() #建立表:“requirement” self.dataSheet=self.wkbook.add_sheet("requirement") #把資料按 按照相應格式寫入excel表中 self.writeDataToExcel() #儲存檔案 self.savaExcel() except Exception,e: print "GenTestCase init error:",e def writeDataToExcel(self): try: #埋點測試用例包含的相關屬性,即表頭 firstLine=[u"埋點事件",u"頁面",u"serviceId",u"屬性名", u"屬性值",u"屬性資訊",u"埋點規則",u"版本",u"IOS開發",u"安卓開發",u"建立時間",u"測試人員",u"測試狀態"] #在表的起始行寫入表頭資料 try: for index in range(len(firstLine)): self.dataSheet.write(0,index,firstLine[index]) except Exception,e: print "Creat Head Error:",e #把csv中讀取的資料賦給變數dataBody dataBody=self.dataInfor.buffer #設定個函式,用來記錄要合併的起始行 currentrow=1 #對資料進行迴圈取值,由於第一行的資料不是需要的資料 #所以從第二個元素開始 try: for rowNum in range(1,len(dataBody)): #對於每個子list中的值,依次寫入相關單元格 for index in range(len(dataBody[rowNum])): #判斷行是否大於1,為以下比較建立條件 if rowNum>1: #把資料的當前行的元素與上一行元素作比較 #如果不相等執行if語句 try: if dataBody[rowNum-1][0]!=dataBody[rowNum][0] : print currentrow,rowNum #由於存在特殊情況,當前行號要為1 #針對特定的資料規則從和並前三行和後七行 if currentrow==1: for cols in range(3): #獲取當前在合併單元格要儲存的值 cellValue=dataBody[currentrow][cols] #對單元格的值進行解碼 cellValue=cellValue.decode("gbk") #對單元格字串進行加u #用來解決UnicodeDecodeError 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,13): 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 except Exception,e: print "Merage cell Error:",e for cols in range(3,6): cellValue=dataBody[rowNum][cols] cellValue=cellValue.decode("gbk") data=u"%s" %(cellValue) self.dataSheet.write(rowNum,cols,data) except Exception,e: print "Write Data Error:",e except Exception,e: print "Write Data TO Excel Error:",e def savaExcel(self): try: savePath=self.dataInfor.fmObj.RequmentPath() self.wkbook.save(savePath) except Exception,e: print "Save Excel Error:",e def test(): GenTestCase() if __name__=="__main__": test()