02 设置格式

文章引用自网易云课堂《用Python自动办公,做职场高手》
网址:https://study.163.com/course/introduction/1006277004.htm
测试文件:https://share.weiyun.com/5dHrT9r

一、 待填入数据表格

XX公司7月5日入库表:微软雅黑,22号,加粗
表格:微软雅黑,18号,加粗,细实线边框
如图


日统计.jpg

二、填入数据

创建一个副本,填入数据并保存。系统默认不带格式填写

from xlutils.copy import copy    # 引用xlutils的复制功能用于复制Excel工作簿,包括其格式 (xlutils对于xlsx兼容性较差,建议使用xls)
import xlrd
import xlwt
tem_excel = xlrd.open_workbook('d:/auto_office/excel/日统计.xls', formatting_info = True)    # 带着格式打开'日统计表.xls'
tem_sheet = tem_excel.sheet_by_index(0)     # 通过索引读取工作表1

new_excel = copy(tem_excel)    # 复制tem_excel模板
new_sheet = new_excel.get_sheet(0)    # 获取新new_excel的工作表1

#先尝试着往表里填写一些内容
new_sheet.write(2,1,12)    # 在第3行第2列写入12
new_sheet.write(3,1,18)    # 同理
new_sheet.write(4,1,19)    # 同理
new_sheet.write(5,1,15)    # 同理
new_excel.save('d:/auto_office/excel/填写.xls')

填写.jpg

三、设置格式

# 发现表格是填写时是不带格式的,所以我们创建一个格式

style = xlwt.XFStyle()    # 初始化一个样式,style

font = xlwt.Font()    # 初始化一个字体
font.name = '微软雅黑'    # 选择'微软雅黑'字体
font.bold = True    # 加粗,不加粗写False
font.height = 360    # 设置字体大小,18号 * 系数20 = 360
style.font = font    # style的字体样式为上面的font

borders = xlwt.Borders()    # 初始化单元格的表框
borders.top = xlwt.Borders.THIN    # 添加细线上边,THIN表示细线
borders.bottom = xlwt.Borders.THIN    # 添加下边
borders.left = xlwt.Borders.THIN    # 添加细线左边
borders.right = xlwt.Borders.THIN    # 添加细线右边
style.borders = borders    # style的边框样式为上面的borders

alignment = xlwt.Alignment()    # 初始化对齐
alignment.horz = xlwt.Alignment.HORZ_CENTER    # 水平居中
alignment.vert = xlwt.Alignment.VERT_CENTER    # 垂直居中
style.alignment = alignment    # style的对齐方式为上面的alignment

四、带格式填入数据

设置好格式后,以带格式的方式将数据填入日统计表

new_sheet.write(2,1,12,style)    # 在第3行第2列写入12,带设置好的style格式
new_sheet.write(3,1,18,style)    # 同理
new_sheet.write(4,1,19,style)    # 同理
new_sheet.write(5,1,15,style)    # 同理
new_excel.save('d:/auto_office/excel/填写(带格式).xls')

填写(带格式).jpg

五、总结

流程.png
Excel样式:style.png

你可能感兴趣的:(02 设置格式)