Python设置Excel样式
前面已经详细讲解过使用Python对Excel表格进行读、写操作,本文主要讲解下使用Python设置Excel表格的样式。
深入学习请参考openpyxl官方文档: https://openpyxl.readthedocs.io/en/stable/
import openpyxl
from openpyxl.styles import Font, Color # 设置字体、aRGB颜色
from openpyxl.styles import PatternFill, colors # 设置背景色、颜色
from openpyxl.styles import Border, Side # 设置边框
from openpyxl.styles import Alignment # 设置单元格文字对齐方式、自动换行
# 新建工作簿
wb = openpyxl.Workbook()
ws = wb.active
# 1.单元格设置字体大小、类型名称、是否加粗/斜体/删除线、颜色
ws.title = 'setFont'
ws['B3'] = 'italic24Font'
# 创建一个字体对象,设置为24pt,Italic(斜体),添加删除线(strike)
italic24Font = Font(size=24, italic=True, strike=True)
ws['B3'].font = italic24Font
ws['A1'] = 'Bold Red Times New Roman'
# 创建一个字体对象,设置为Times New Roman,加粗,红色
boldRedFont = Font(name='Times New Roman', bold=True, color='00FF0000')
ws['A1'].font = boldRedFont
# 2.单元格设置计算公式
ws = wb.create_sheet('Formula')
ws['A1'] = 200
ws['A2'] = 100
ws['A3'] = 50
ws['A4'] = 300
# 下面的计算公式与实际操作Excel表格时设置的公式相同
ws['A5'] = '= A1 + A2'
ws['A6'] = '= SUM(A1:A4)'
ws['A7'] = '= A1*A2'
ws['A8'] = '= A1/A2'
# 3.单元格设置行高、列宽
ws = wb.create_sheet('dimentions') # dimentions 尺寸
ws['A1'] = 'Tall row'
ws['B2'] = 'Wide column'
ws.row_dimensions[1].heigth = 50 # 设置第一行的行高50
ws.column_dimensions['B'].width = 20 # 设置B列的列宽20
# 4.单元格设置背景色
ws = wb.create_sheet('background')
ws['A1'] = 'Set background'
color1 = PatternFill("solid", fgColor="0099CC00")
ws['A1'].fill = color1
说明:aRGB颜色参考下方
# 5.单元格设置边框
ws = wb.create_sheet('frame')
border = Border(left=Side(border_style='thin', color='000000'),
right=Side(border_style='thin', color='000000'),
top=Side(border_style='thin', color='000000'),
bottom=Side(border_style='thin', color='000000')) # 设置成细的,黑色边框
ws['A1'].border = border
# ws['A1:D5'].border = border
# 说明:边框的样式有很多种,可以查阅openpyxl官方文档。
# 6.设置单元格文字对齐方式
ws = wb.create_sheet('alignment_method')
ws['A1'] = "Learning cell's alignment_method"
align = Alignment(horizontal='left', vertical='center', wrap_text=True)
ws['A1'].alignment = align
# 说明:
# horizontal代表水平方向,可以左对齐left,还有居中center和右对齐right,分散对齐distributed,跨列居中centerContinuous,两端对齐justify,填充fill,常规general
# vertical代表垂直方向,可以居中center,还可以靠上top,靠下bottom,两端对齐justify,分散对齐distributed
# 自动换行:wrap_text,这是个布尔类型的参数,这个参数还可以写作wrapText
# 7.合并单元格
ws = wb.create_sheet('merge_cells')
ws.merge_cells('A1:D3')
ws['A1'] = 'Twelve cells merged together'
ws.merge_cells('C5:D5')
ws['C5'] = 'Two cells merged together'
# 8.拆分单元格
ws = wb.copy_worksheet(wb['merge_cells']) # 拷贝之前的merge_cells表单
ws.title = 'unmerge_cells'
ws.unmerge_cells('A1:D3')
ws.unmerge_cells('C5:D5')
# 9.冻结单元格
ws.freeze_panes = 'B1' # 冻结第一列
ws.freeze_panes = 'A2' # 冻结第一行
ws.freeze_panes = 'B2' # 同时冻结第一行和第一列
wb.save('style.xlsx')
执行程序后,打开生成的style.xlsx,会看到各个表单的样式设置效果:
最后,喜欢的朋友麻烦点赞、推荐给更多热爱学习朋友,更多精彩内容后续持续更新!