2)获取表格中格子的字体样式
from openpyxl.styles import Font from openpyxl import load_workbook workbook = load_workbook(filename="花园.xlsx") sheet = workbook.active cell = sheet["A2"] font = cell.font print(font.name, font.size, font.bold, font.italic, font.color)
结果如下:
3)设置对齐样式
Alignment(horizontal=水平对齐模式,vertical=垂直对齐模式,text_rotation=旋转角度,wrap_text=是否自动换行)
水平对齐:‘distributed’,‘justify’,‘center’,‘leftfill’, ‘centerContinuous’,‘right,‘general’;
垂直对齐:‘bottom’,‘distributed’,‘justify’,‘center’,‘top’;
from openpyxl.styles import Alignment from openpyxl import load_workbook workbook = load_workbook(filename="花园.xlsx") sheet = workbook.active cell = sheet["A1"] alignment = Alignment(horizontal="center",vertical="center",text_rotation=45,wrap_text=True) cell.alignment = alignment workbook.save(filename = "花园.xlsx")
结果如下:
4)设置边框样式
Side(style=边线样式,color=边线颜色)
Border(left=左边线样式,right=右边线样式,top=上边线样式,bottom=下边线样式)
style参数的种类: 'double, ‘mediumDashDotDot’,
‘slantDashDot’,‘dashDotDot’,‘dotted’,‘hair’, 'mediumDashed, ‘dashed’, ‘dashDot’, ‘thin’,‘mediumDashDot’,‘medium’, 'thick’from openpyxl.styles import Side,Borderfrom openpyxl import load_workbook workbook = load_workbook(filename="花园.xlsx") sheet = workbook.active cell = sheet["D6"] side1 = Side(style="thin",color="FF0000") side2 = Side(style="thick",color="FFFF0000") border = Border(left=side1,right=side1,top=side2,bottom=side2) cell.border = border workbook.save(filename = "花园.xlsx")
结果如下:
5)设置填充样式
PatternFill(fill_type=填充样式,fgColor=填充颜色)
GradientFill(stop=(渐变颜色1,渐变颜色2……))
from openpyxl.styles import PatternFill,GradientFill from openpyxl import load_workbook workbook = load_workbook(filename="花园.xlsx") sheet = workbook.active cell_b9 = sheet["B9"] pattern_fill = PatternFill(fill_type="solid",fgColor="99ccff") cell_b9.fill = pattern_fill cell_b10 = sheet["B10"] gradient_fill = GradientFill(stop=("FFFFFF","99ccff","000000")) cell_b10.fill = gradient_fill workbook.save(filename = "花园.xlsx")
结果如下: