import xlrd import xlwt from xlutils.copy import copy class Excel: """ Excel表格封裝 1. 讀取Excel的數據 2. 數據寫入到Excel中 """ def __init__(self): self.path = "E:\z_shishi\data\param.xlsx" def get_data(self,rowx, colx): """獲取Excel中的值""" sheet = xlrd.open_workbook(self.path) index = sheet.sheet_by_index(0) value = index.cell_value(rowx, colx) return value def write_data(self,P_F,style): """寫入Excel""" rb =xlrd.open_workbook("E:\z_shishi\data\param.xlsx") wb = copy(rb) s = wb.get_sheet(0) #設置樣式 s.write(2, 5,P_F,style) wb.save("change06.xls") return wb def set_style(self,color): """寫入數據庫的樣式""" font = xlwt.Font() font.name = "Times New Roman" font.colour_index = color style = xlwt.XFStyle() style.font = font return style def result_write(self,res,color): """對結果進行判斷,如果結果為0(成功),寫入Excel 紅色PASS 如果結果為1(失敗),寫入Excel 藍色Fail 11為銀綠色 12為藍色 """ try: if res==0: self.write_data("PASS",self.set_style(color) ) elif res==1: self.write_data("PASS", self.set_style(12)) print ("finished") except Exception as e : print ("寫入Excel時不能打開Excel文檔") # if res==0: #不寫類,直接使用函數調用 # # write_data("PASS",set_style(color)) # elif res==1: # write_data("FAIL",set_style(12)) # print ("finished") if __name__=="__main__": excel = Excel() excel.result_write(0,2)