python导出excel之xlwt模块的使用

xlwt模块可以用来导出excel表, 但该模块支持的excel版本较低 (97 - 2003)

1. 安装xlwt模块

pip3 install xlwt

2. 使用xlwt模块

import xlwt

# 创建表, 默认字符编码为ascii
workbook = xlwt.Workbook(encoding= 'ascii')
# 在当前表中创建工作薄, data为工作薄名称
worksheet = workbook.add_sheet('data')

# 生成单元格样式的方法
def title_style():
    font = xlwt.Font() # 创建字体
    font.name = 'SimSun' # 宋体
    font.height = 20 * 18 # 设置字体大小, 18为实际字体大小, 20为固定值

    style = xlwt.XFStyle() # 创建style
    style.alignment.horz = 2 # 设置字体居中
    style.font = font # style的字体为上面定义的字体
    return style

# 合并单元格, 前四个参数为需要合并的单元格的序号, Test为单元格内容, style为单元格样式
worksheet.write_merge(0, 0, 0, 4, label = '用户列表',style = title_style())

# 设置列宽, 3为列的数目, 12为列的宽度, 256为固定值
for i in range(3):
    worksheet.col(i).width = 256 * 12

# 设置单元格行高, 25为行高, 20为固定值
worksheet.row(1).height_mismatch = True
worksheet.row(1).height = 20 * 25

# 向单元格写入数据
worksheet.write(1, 0, '姓名')
worksheet.write(1, 1, '年龄')
worksheet.write(1, 2, '性别')

# 保存xls
workbook.save('demo.xls')

worksheet还可以设置许多单元格的样式, 这里只列出了一些

猜你喜欢

转载自blog.csdn.net/zwliang98/article/details/83545405