搬運出處: https://blog.csdn.net/weixin_44065501/article/details/88899257
Python模塊xlwt對excel進行寫入操作: https://www.cnblogs.com/machangwei-8/p/10738244.html
Python3使用xlwt時寫入文檔字體顏色和邊框樣式: https://www.cnblogs.com/xiaodingdong/p/8012282.html
Python3使用xlwt設置單元格: https://www.jianshu.com/p/0f0cfffc949b
# coding:utf-8 import patterns as patterns import xlwt import time i = 0 book = xlwt.Workbook(encoding='utf-8') sheet = book.add_sheet('sheet1', cell_overwrite_ok=True) # 如果出現報錯:Exception: Attempt to overwrite cell: sheetname='sheet1' rowx=0 colx=0 # 需要加上:cell_overwrite_ok=True) # 這是因為重復操作一個單元格導致的 while i < 64: # 為樣式創建字體 font = xlwt.Font() # 字體類型 font.name = 'name Times New Roman' # 字體顏色 font.colour_index = i # 字體大小,11為字號,20為衡量單位 font.height = 20*11 # 字體加粗 font.bold = False # 下划線 font.underline = True # 斜體字 font.italic = True # 設置單元格對齊方式 alignment = xlwt.Alignment() # 0x01(左端對齊)、0x02(水平方向上居中對齊)、0x03(右端對齊) alignment.horz = 0x02 # 0x00(上端對齊)、 0x01(垂直方向上居中對齊)、0x02(底端對齊) alignment.vert = 0x01 # 設置自動換行 alignment.wrap = 1 # 設置邊框 borders = xlwt.Borders() # 細實線:1,小粗實線:2,細虛線:3,中細虛線:4,大粗實線:5,雙線:6,細點虛線:7 # 大粗虛線:8,細點划線:9,粗點划線:10,細雙點划線:11,粗雙點划線:12,斜點划線:13 borders.left = 1 borders.right = 2 borders.top = 3 borders.bottom = 4 borders.left_colour = i borders.right_colour = i borders.top_colour = i borders.bottom_colour = i # 設置列寬,一個中文等於兩個英文等於兩個字符,11為字符數,256為衡量單位 sheet.col(1).width = 11 * 256 # 設置背景顏色 pattern = xlwt.Pattern() # 設置背景顏色的模式 pattern.pattern = xlwt.Pattern.SOLID_PATTERN # 背景顏色 pattern.pattern_fore_colour = i # 初始化樣式 style0 = xlwt.XFStyle() style0.font = font style1 = xlwt.XFStyle() style1.pattern = pattern style2 = xlwt.XFStyle() style2.alignment = alignment style3 = xlwt.XFStyle() style3.borders = borders # 設置文字模式 font.num_format_str = '#,##0.00' sheet.write(i, 0, u'字體', style0) sheet.write(i, 1, u'背景', style1) sheet.write(i, 2, u'對齊方式', style2) sheet.write(i, 3, u'邊框', style3) # 合並單元格,合並第2行到第4行的第4列到第5列 sheet.write_merge(2, 4, 4, 5, u'合並') i = i + 1 book.save('E:/test/testfile/test_file'+time.strftime("%Y%m%d%H%M%S")+'.xls')