先定义一段函数,设置单元格样式
def set_style(name, height, bold=False, borders=False):
style = xlwt.XFStyle() # 创建一个样式对象,初始化样式
al = xlwt.Alignment()
al.horz = 0x02 # 设置水平居中
# al.vert = 0x01 # 设置垂直居中
style.alignment = al
#设置字体样式
font = xlwt.Font() # 为样式创建字体
font.name = name
font.bold = bold
font.color_index = 4
font.height = height
#设置单元格边框样式
if borders:
borders = xlwt.Borders()
borders.left = 6
borders.right = 6
# borders.top= 6
# borders.bottom= 6
style.borders = borders
style.font = font
return style
xlwt模块写入Excel数据时,用函数调用的方法设置样式
# 写入数据
style1 = set_style('Arial', 220, False, True) # 左右边框
style2 = xlwt.easyxf('pattern: pattern solid, fore_colour 29') # 红色背景
worksheet.write(idx, 5, value[i]['classify']['terrain'][1], style1)
worksheet.write(idx, 6, value[i]['classify']['tree'][1], style2)
在写入数据的过程中,可以调用一些Excel内置函数,以调用SUBSTITUTE函数为例
worksheet.write(idx, 1, xlwt.Formula(
'"@teleport_camera " & SUBSTITUTE(A' + str(idx + 1) + ', "_", " ") & " 0 0 1"'))
实现效果如下