安装模块
快速上手 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 import xlwtfile = xlwt.Workbook(encoding='ascii' ) table = file.add_sheet('sheet name' ) """ 如果对一个单元格重复操作 会引发Exception: Attempt to overwrite cell 所以在打开时加cell_overwrite_ok=True 解决 """ table = file.add_sheet('sheet name' ,cell_overwrite_ok=True ) table.write(0 ,0 ,'test' ) file.save('demo.xls' )
行高列宽 1 2 3 4 table.row(0 ).height_mismatch = True table.row(0 ).height = 800 table.col(0 ).width = 256 * 12
风格样式
类
作用
Font()
用来设置单元格字体内容,如字体类型、大小等
borders()
设置单元格边框线粗细
partern()设置单元格背景颜色
XFStyle()
设置风格类型
alignment()
用来设置了字体水平居中、垂直居中、自动换行
设置单元格风格,写成了一个函数,如下:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 def body_style (pattern=None) : font = xlwt.Font() font.name = "SimSun" font.height = 20 * 12 font.colour_index = 1 font.bold = True style = xlwt.XFStyle() style.alignment.horz = 2 style.alignment.vert = 1 style.alignment.wrap = 1 if pattern: pat = xlwt.Pattern() pat.pattern = 1 pat.pattern_fore_colour = pattern patterni.pattern_back_colour = 35 style.pattern = pat borders = xlwt.Borders() borders.left = 1 borders.right = 1 borders.top = 1 borders.bottom = 1 style.font = font style.borders = borders return style
写入数据 1 2 3 4 5 table.write(m_row, m_col, u'内容' , body_style()) table.write_merge(1 , 2 , m_col, m_col+3 , u'合并的内容' , body_style())
案例书写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 import xlwtdef body_style (patterns=None,bold=False,st=1 ) : font = xlwt.Font() font.name = "SimSun" font.height = 20 * 28 font.colour_index = 0 font.bold = bold style = xlwt.XFStyle() style.alignment.horz = 2 style.alignment.vert = 1 style.alignment.wrap = 1 if patterns: pat = xlwt.Pattern() pat.pattern = st style.pattern = pat borders = xlwt.Borders() borders.left = 1 borders.right = 1 borders.top = 1 borders.bottom = 1 style.font = font style.borders = borders return style workbook = xlwt.Workbook(encoding='utf-8' ) table = workbook.add_sheet('sheet1' ,cell_overwrite_ok=True ) header_cls=['python' ,'java' ,'c++' ] header_row=['语言' ,'使用人数' ,'使用率' ,'涉及行业' ,'备注' ] title='当前热门语言统计' table.write_merge(0 ,0 ,0 ,4 ,title,body_style(patterns=1 ,bold=True ,st=2 )) for i in range(len(header_row)): table.row(i).height = 80 table.col(i).width = 256 * 25 table.write(1 ,i,header_row[i],body_style(bold=False ,st=1 )) for i in range(len(header_cls)): table.write(2 +i,0 ,header_cls[i],body_style(bold=False ,st=1 )) workbook.save('测试.xls' )