本文主要是介绍Python之xlwt创建Excel,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import xlwt import datetime #设置表格样式 def set_style(name,height,bold=False):style = xlwt.XFStyle()# 初始化样式,font = xlwt.Font() # 为样式创建字体font.name = name#字体样式font.bold = bold# 粗体font.underline = True # 下划线font.italic = True # 斜体字font.colour_index = 2font.height = height #字高style.font = fontreturn style#写Excel def write_excel():f = xlwt.Workbook(encoding='ascii')#创建对象,指定编码为'ascii'sheet1 = f.add_sheet('学生',cell_overwrite_ok=True)row0= ["姓名","年龄","出生日期","爱好"]colum0 = ["张三","李四","Python","小明","小红","无名"] #写第一行for i in range(0,len(row0)):sheet1.write(0,i,row0[i],set_style('Times New Roman',220,False))# sheet1.write(行,列,值,格式) #写第一列for i in range(0,len(colum0)):sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True))#sheet1.write(行,列,值,格式)sheet1.write(1,3,'aaaa',set_style('Times New Roman',220,True))#sheet1.write(行,列,值,格式)sheet1.write_merge(6,6,1,3,'未知')#合并行单元格sheet1.write_merge(行1,行2,列1,列2)从行1-行2,列1到列2)sheet1.write_merge(1,2,3,3,'打游戏')#合并列单元格sheet1.write_merge(4,5,3,3,'打篮球')sheet2 = f.add_sheet('yonghu', cell_overwrite_ok=False)row0 = ["姓名", "年龄", "出生日期", "爱好"]# 写第一行for i in range(0, len(row0)):sheet2.write(0, i, row0[i]) # sheet1.write(行,列,值,格式)sheet2.write(1,0,"我爱你")sheet2.write(3, 5, "我爱你35")# 设置列1单元格宽度sheet2.col(0).width = 3333sheet2.write(2,0, label = 'this is test')style = xlwt.XFStyle()style.num_format_str = 'D-MMM-YY' # 设置单元格时间格式Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0sheet2.write(2,1,datetime.datetime.now(),style)f.save('test.xls')if __name__ == '__main__':write_excel()
这篇关于Python之xlwt创建Excel的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!