当前位置: 首页 > 工具软件 > WriteExcel > 使用案例 >

python xlwt write excel 设置excel单元格属性、字体、颜色、合并单元格

柳修平
2023-12-01
import xlwt
def excel_style(font_height, align_h, align_v, align_wrap=1, align_shri=0, pattern_color=None, borders_set=None):
    font = xlwt.Font()
    font.name = '宋体'
    font.height = font_height
    # 设置单元格对齐方式
    alignment = xlwt.Alignment()
    # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
    alignment.horz = align_h
    # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
    alignment.vert = align_v
    # 1-自动换行,0-不自动换行
    alignment.wrap = align_wrap
    # 缩小字体填充
    alignment.shri = align_shri

    style = xlwt.XFStyle()
    style.font = font
    style.alignment = alignment

    if borders_set is not None:
        # 设置边框
        borders = xlwt.Borders()
        # 细实线:1,小粗实线:2,细虚线:3,中细虚线:4,大粗实线:5,双线:6,细点虚线:7
        # 大粗虚线:8,细点划线:9,粗点划线:10,细双点划线:11,粗双点划线:12,斜点划线:13
        borders.left = borders_set
        borders.right = borders_set
        borders.top = borders_set
        borders.bottom = borders_set
        borders.left_colour = 8
        borders.right_colour = 8
        borders.top_colour = 8
        borders.bottom_colour = 8
        style.borders = borders

    # 设置背景颜色的模式
    if pattern_color is not None:
        pattern_top = xlwt.Pattern()
        pattern_top.pattern = xlwt.Pattern.SOLID_PATTERN
        pattern_top.pattern_fore_colour = pattern_color
        style.pattern = pattern_top
    return style

write_excel = xlwt.Workbook()
flight_plan_st = write_excel.add_sheet('计划')  # 添加sheet
flight_info_st = write_excel.add_sheet('动态')
#  去掉页眉页脚,否则打印出来会有东西
flight_plan_st.show_headers = False
flight_plan_st.header_str = b''
flight_plan_st.footer_str = b''
# 合并第0行到第1行的第0列到第7列
style = excel_style(20*18, 0x02, 0x01)
flight_plan_st.write_merge(0, 1, 0, 6, date + "航班计划", style)
style = excel_style(20*12, 0x02, 0x01, pattern_color=22, borders_set=1)
flight_plan_st.write(2, 0, "机号", style)
flight_plan_st.write(2, 1, "性质", style)
flight_plan_st.write(2, 2, "班号", style)
flight_plan_st.write(2, 3, "飞场", style)

for i in range(0, 4):
    # 设置列宽,一个中文等于两个英文等于两个字符,11为字符数,256为衡量单位
    flight_plan_st.col(i).width = 14 * 245
tall_style = xlwt.easyxf('font:height 360')  # 24pt,设置行高
flight_plan_st.row(0).set_style(tall_style)
flight_plan_st.row(1).set_style(tall_style)
tall_style = xlwt.easyxf('font:height 279')  # 18pt
flight_plan_st.row(2).set_style(tall_style)
write_excel.save("test.xls")
 
 类似资料: