python excel單元格及樣式:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*-” #只對當前文件的中文編碼有效 3 # Filename : Write_excel_Format.py 4 import os 5 import time 6 import xlwt 7 8 #檢測當前目錄下是否有TestData2.xls文件,如果有則清除以前保存文件 9 filename = 'TestData2.xls' 10 if os.path.exists(filename): 11 os.remove(filename) 12 13 #打印讀取到當前系統時間 14 print(time.strftime("%Y-%m-%d",time.localtime(time.time()))) 15 16 wbk = xlwt.Workbook(encoding='utf-8') 17 sheet = wbk.add_sheet('new sheet 1', cell_overwrite_ok=True) #第二參數用於確認同一個cell單元是否可以重設值。 18 style = xlwt.XFStyle() #賦值style為XFStyle(),初始化樣式 19 20 #設置居中 21 al = xlwt.Alignment() 22 al.horz = 0x02 # 設置水平居中 23 al.vert = 0x01 # 設置垂直居中 24 style.alignment = al 25 26 27 # 設置單元格背景顏色 28 for i in range(0x00,0xff): # 設置單元格背景顏色 29 pattern =xlwt.Pattern() # 創建一個模式 30 pattern.pattern = xlwt.Pattern.SOLID_PATTERN # 設置其模式為實型 31 pattern.pattern_fore_colour = i 32 33 # 設置單元格背景顏色 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, the list goes on... 34 style.pattern = pattern # 將賦值好的模式參數導入Style 35 Line_data = (u'測試表') #創建一個Line_data列表,並將其值賦為測試表,以utf-8編碼時中文前加u 36 sheet.write_merge(i, i, 0, 2, Line_data, style) #以合並單元格形式寫入數據,即將數據寫入以第1/2/3列合並德單元格內 37 38 39 # 設置單元格內字體樣式 40 for i in range(0x00,0xff): 41 fnt = xlwt.Font() # 創建一個文本格式,包括字體、字號和顏色樣式特性 42 fnt.name = u'微軟雅黑' # 設置其字體為微軟雅黑 43 fnt.colour_index = i # 設置其字體顏色 44 fnt.bold = True 45 style.font = fnt #將賦值好的模式參數導入Style 46 47 #行合並 48 #以合並單元格形式寫入數據,即將數據寫入以第4/5/6列合並德單元格內 49 sheet.write_merge(i,i,3,5,Line_data,style) 50 51 52 # 設置單元格下框線樣式 53 for i in range(0, 0x53): 54 borders = xlwt.Borders() 55 borders.left = i 56 borders.right = i 57 borders.top = i 58 borders.bottom = i 59 style.borders = borders #將賦值好的模式參數導入Style 60 sheet.write_merge(i,i,6,8,Line_data,style) #以合並單元格形式寫入數據,即將數據寫入以第4/5/6列合並德單元格內 61 62 63 # 設置單元格下列寬樣式 64 for i in range(6, 15): 65 sheet.write(0,i,Line_data,style) 66 sheet.col(i).width = 0x0d00 + i*50 67 68 #設置居中 69 al = xlwt.Alignment() 70 al.horz = 0x02 # 設置水平居中 71 al.vert = 0x01 # 設置垂直居中 72 style.alignment = al 73 74 75 #行合並及列表合並 76 sheet.write_merge(2,2,11,13,"行合並3列",style) 77 sheet.write_merge(3,5,12,12,"列合並3列",style) 78 79 #插入圖片 80 path_py = ".\images\python.bmp" #讀取插入圖片以.py運行時路徑,images和.py在同一目錄下 81 path_exe = ".\images\python.bmp" #讀取插入圖片以.exe運行時路徑,.exe可以移到其他任意目錄下運行但images和.exe在同一目錄下 82 #path = cur_file_dir(path_py,path_exe) #獲取文件的相對路徑 83 path=os.path.abspath(path_py) 84 filename = path #檢測當前目錄下是否有python.bmp圖片, 85 if os.path.exists(filename): 86 print(u'python.bmp圖片存在') 87 else: 88 print(u'python.bmp圖片不存在') 89 sheet.insert_bitmap(path, 2, 9) #插入一個圖片 90 91 wbk.save('TestData2.xls') #保存TestData2.xls文件,保存到腳本或exe文件運行的目錄下 92 input("Enter enter key to exit...") #插入一個輸入命令,方便運行exe時一閃而過不到打印信息
上代碼:
顯示結果: