lab-zj

搬运出处: https://blog.csdn.net/weixin_44065501/article/details/88899257

Python模块xlwt对excel进行写入操作: https://www.cnblogs.com/machangwei-8/p/10738244.html

Python3使用xlwt时写入文档字体颜色和边框样式: https://www.cnblogs.com/xiaodingdong/p/8012282.html

Python3使用xlwt设置单元格: https://www.jianshu.com/p/0f0cfffc949b

# coding:utf-8
import patterns as patterns
import xlwt
import time
i = 0
book = xlwt.Workbook(encoding=\'utf-8\')
sheet = book.add_sheet(\'sheet1\', cell_overwrite_ok=True)
# 如果出现报错:Exception: Attempt to overwrite cell: sheetname=\'sheet1\' rowx=0 colx=0
# 需要加上:cell_overwrite_ok=True)
# 这是因为重复操作一个单元格导致的

while i < 64:
        # 为样式创建字体
        font = xlwt.Font()
        
        # 字体类型
        font.name = \'name Times New Roman\'
        # 字体颜色
        font.colour_index = i
        # 字体大小,11为字号,20为衡量单位
        font.height = 20*11
        # 字体加粗
        font.bold = False
        # 下划线
        font.underline = True
        # 斜体字
        font.italic = True

        # 设置单元格对齐方式
        alignment = xlwt.Alignment()
        # 0x01(左端对齐)、0x02(水平方向上居中对齐)、0x03(右端对齐)
        alignment.horz = 0x02
        # 0x00(上端对齐)、 0x01(垂直方向上居中对齐)、0x02(底端对齐)
        alignment.vert = 0x01

        # 设置自动换行
        alignment.wrap = 1

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

        # 设置列宽,一个中文等于两个英文等于两个字符,11为字符数,256为衡量单位
        sheet.col(1).width = 11 * 256

        # 设置背景颜色
        pattern = xlwt.Pattern()
        # 设置背景颜色的模式
        pattern.pattern = xlwt.Pattern.SOLID_PATTERN
        # 背景颜色
        pattern.pattern_fore_colour = i

        # 初始化样式
        style0 = xlwt.XFStyle()
        style0.font = font

        style1 = xlwt.XFStyle()
        style1.pattern = pattern

        style2 = xlwt.XFStyle()
        style2.alignment = alignment

        style3 = xlwt.XFStyle()
        style3.borders = borders

        # 设置文字模式
        font.num_format_str = \'#,##0.00\'

        sheet.write(i, 0, u\'字体\', style0)
        sheet.write(i, 1, u\'背景\', style1)
        sheet.write(i, 2, u\'对齐方式\', style2)
        sheet.write(i, 3, u\'边框\', style3)

        # 合并单元格,合并第2行到第4行的第4列到第5列
        sheet.write_merge(2, 4, 4, 5, u\'合并\')
        i = i + 1

book.save(\'E:/test/testfile/test_file\'+time.strftime("%Y%m%d%H%M%S")+\'.xls\')

分类:

技术点:

相关文章:

  • 2022-02-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
  • 2022-12-23
  • 2021-05-23
猜你喜欢
  • 2022-12-23
  • 2021-10-13
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案