操作 excel 写 xlwt

来源:互联网 发布:kdl32w600d安装软件 编辑:程序博客网 时间:2024/06/06 14:29
安装相关模块 pip install xlwt

import xlwt# 简单的写入# write_merge(x, x + m, y, w + n, string, sytle)# x表示行,y表示列,m表示跨行个数,n表示跨列个数,string表示要写入的单元格内容,style表示单元格样式。其中,x,y,w,h,都是以0开始计算的。# 这个和xlrd中的读合并单元格的不太一样。# 如上述:sheet1.write_merge(21,21,0,1,u'合计',set_style('Times New Roman',220,True))# 即在22行合并第1,2列,合并后的单元格内容为"合计",并设置了style。# 如果需要创建多个sheet,则只要f.add_sheet即可。'''设置单元格样式'''def set_style(name, height, bold=False):    # 初始化样式    style = xlwt.XFStyle()    # 为样式创建字体    font = xlwt.Font()    font.name = name    font.bold = bold    font.color_index = 4    font.height = height    style.font = font    return styledef write_excel():    f = xlwt.Workbook()    '''    创建第一个 Sheet:    '''    sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)    row0 = [u'业务', u'状态', u'北京', u'上海', u'广州', u'深圳', u'状态小计', u'合计']    column0 = [u'机票', u'船票', u'火车票', u'汽车票', u'其它']    status = [u'预订', u'出票', u'退票', u'业务小计']    # 生成第一行    for i in range(0, len(row0)):        sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))    # 生成第一列和最后一列(合并4行)    i, j = 1, 0    while i < 4*len(column0) and j < len(column0):        sheet1.write_merge(i, i+3, 0, 0, column0[j], set_style('Arial',220,True))        sheet1.write_merge(i, i+3, 7, 7)        i += 4        j += 1    sheet1.write_merge(21, 21, 0, 1, u'合计', set_style('Times New Roman',220,True))    #生成第二列    i = 0    while i < 4*len(column0):        for j in range(0, len(status)):            sheet1.write(j+i+1, 1, status[j])        i += 4    '''        创建第二个 sheet:            sheet2    '''    sheet2 = f.add_sheet(u'sheet2', cell_overwrite_ok=True)    row0 = [u'姓名', u'年龄', u'出生日期', u'爱好', u'关系']    column0 = [u'小杰', u'小胖', u'小明', u'大神', u'大仙', u'小敏', u'无名']    #生成第一行    for i in range(0, len(row0)):        sheet2.write(0, i, row0[i], set_style('Times New Roman',220,True))    #生成第一列    for i in range(0, len(column0)):        sheet2.write(i+1, 0, column0[i], set_style('Times New Roman',220))    sheet2.write(1, 2, '1991/11/11')    sheet2.write_merge(7, 7, 2, 4, u'暂无')    sheet2.write_merge(1, 2, 4, 4, u'好朋友')    f.save('demo1.xlsx')if __name__ == '__main__':    write_excel()
0 0