import xlwt
def set_style(name, height, bold):
style = xlwt.XFStyle() # 初始化表格样式
font = xlwt.Font() # 为样式创建字体
# print(font)
font.name = name #字体由函数传入
font.bold = bold
font.color_index = 4
font.height = height
style.font = font
return style
def write_excel(colunm1,colunm2,colunm3,filename):
# style_compression=2 插入内容很大时添加,encoding='utf-8' 插入汉字时添加
f = xlwt.Workbook(style_compression=2,encoding='utf-8') #创建工作簿
sheet1 = f.add_sheet(u"s", cell_overwrite_ok=True)
sheet2 = f.add_sheet(u"t", cell_overwrite_ok=True)
sheet3 = f.add_sheet(u"w", cell_overwrite_ok=True)
colunm0 = ['ID','标记','序列','版本号','OldID','Old标记']
for a in range(0,len(colunm0)):
sheet1.write(0, a, colunm0[a], set_style('Times New Roman', 220, False))
sheet2.write(0, a, colunm0[a], set_style('Times New Roman', 220, False))
sheet3.write(0, a, colunm0[a], set_style('Times New Roman', 220, False))
for i in range(0, len(colunm1)):
for j in range(0, len(colunm1[i])):
sheet1.write(i+1, j, colunm1[i][j], set_style('Times New Roman', 220, False))
for i in range(1, len(colunm2)):
for j in range(0, len(colunm2[i])):
sheet2.write(i+1, j, colunm2[i-1][j], set_style('Times New Roman', 220, False))
for i in range(1, len(colunm3)):
for j in range(0, len(colunm3[i-1])):
sheet3.write(i+1, j, colunm3[i-1][j], set_style('Times New Roman', 220, False))
path = "E:\python" + "\\" + filename + '.xlsx'
f.save(path)
if __name__ == '__main__':
a3,a7,a9 = [[] for x in range(3)]
filename = 'test'
a = [[1,2,3,'v130',2,3],[2,4,2,'v275',1,0],[1,8,3,'v131',2,3],['',2,3,'v133',1,3],[1,2,3,'v298',2,3],[1,3,3,'v277',2,3]]
for i in range(0,len(a)):
if '13' in a[i][3]:
a3.append(a[i])
elif '27' in a[i][3]:
a7.append(a[i])
else:
a9.append(a[i])
write_excel(a3,a7,a9,filename)
自动形成的文档内容如下图:
根据版本号写入不同的sheet