python 按固定格式資料生成excel報表原始碼
阿新 • • 發佈:2019-02-04
# -*- coding: utf-8 -*- __author__ = 'hepengfei' #A:B:C #X:2:3 #參考:http://www.cnblogs.com/snow-backup/p/4021554.html import xlwt from datetime import datetime def writeContent(content,startLine=0,startRow=0,isTitle=0): style0 = xlwt.easyxf('font: name Times New Roman, color-index black, bold on', num_format_str='#,##0.00') # 新增cell的邊框 # Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines. borders = xlwt.Borders() # Create Borders borders.left = xlwt.Borders.THIN # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D. borders.right = xlwt.Borders.THIN borders.top = xlwt.Borders.THIN borders.bottom = xlwt.Borders.THIN borders.left_colour = 0x40 borders.right_colour = 0x40 borders.top_colour = 0x40 borders.bottom_colour = 0x40 style0.borders = borders # Add Borders to Style if isTitle == 1: # 設定cell的背景顏色 pattern = xlwt.Pattern() # Create the Pattern pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12 pattern.pattern_fore_colour = 22 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on... style0.pattern = pattern # Add Pattern to Style # 設定cell內部定位 alignment = xlwt.Alignment() # Create Alignment alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED style0.alignment = alignment # Add Alignment to Style row = startRow; splitContent = content.split(':'); for i in splitContent: if '\r' in i or '\n' in i : continue; ws.write(startLine, row, i ,style0) row = row+1; wb = xlwt.Workbook() ws = wb.add_sheet('A Test Sheet') writeContent('A:B:C',0,0,1); writeContent('X:2:3',1,0); #ws.write(0, 0, 1234.56, style0) #ws.write(1, 0, datetime.now(), style1) #ws.write(2, 0, 1) #ws.write(2, 1, 1) #ws.write(2, 2, xlwt.Formula("A3+B3")) wb.save('f:/example.xls')