import xlwt class WritrExcel(): def set_style(self,name, height, bold=False): style = xlwt.XFStyle() # 初始化樣式 font = xlwt.Font() # 爲樣式建立字體 font.name = name font.bold = bold font.color_index = 4 font.height = height style.font = font return style #寫入Excel def write_excel(self,path,rows): # 建立工做簿 workbook = xlwt.Workbook(encoding='utf-8') # 建立sheet data_sheet = workbook.add_sheet('Sheet1') #將樣式定義在循環以外 default = self.set_style('Times New Roman', 220, True) j = k = 0 # 循環讀取每一行數據並寫入Excel for row in rows: for i in range(len(row)): try: # 寫入 data_sheet.write((j + k), i, row[i], default) except : print(i) raise # data_sheet.write(1, i, row1[i], self.set_style('Times New Roman', 220, True)) k = k + 1 workbook.save(path) print("寫入文件成功,共" + str(k) + "行數據") if __name__ == '__main__': # 設置路徑 rows = ( ('字段名稱', '大體時段', 'CRNTI', 'CELL-ID'), ('測試0', '15:50:33-15:52:14', '22706', '4190202'), ('測試1', '15:50:33-15:52:14', '22706', '4190202'), ('測試2', '15:50:33-15:52:14', '22706', '4190202') ) path = 'demo.xls' WritrExcel().write_excel(path,rows) print(u'建立demo.xls文件成功')