xlwt 是 Python 用来在 Excel 写入数据和格式化数据的工具包
简单使用
import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('test_sheet')
ws.write(0, 0, '球队')
ws.write(0, 1, '号码')
ws.write(0, 2, '姓名')
ws.write(0, 3, '位置')
wb.save('./myExcel.xls')
Font()
属性:
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
Style()
def set_style(name, height, bold=False, format_str='',align='center'):style = xlwt.XFStyle() font = xlwt.Font() font.name = name font.bold = boldfont.height = heightborders = xlwt.Borders() borders.left = 2borders.right = 2borders.top = 0borders.bottom = 2alignment = xlwt.Alignment() if align== 'center':alignment.horz = xlwt.Alignment.HORZ_CENTERalignment.vert = xlwt.Alignment.VERT_CENTERelse:alignment.horz = xlwt.Alignment.HORZ_LEFTalignment.vert = xlwt.Alignment.VERT_BOTTOMstyle.font = fontstyle.borders = bordersstyle.num_format_str = format_strstyle.alignment = alignmentreturn style
合并
worksheet.write_merge(0, 0, 0, 3, 'First Merge')
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style)
对齐
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER
alignment.vert = xlwt.Alignment.VERT_CENTER
style = xlwt.XFStyle()
style.alignment = alignment
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')
背景色
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 5
style = xlwt.XFStyle()
style.pattern = pattern
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')