跳转至

样式系统概述

Symphra Excel提供了强大而灵活的样式系统,让您能够创建专业美观的Excel文档。

样式架构

样式系统采用组件化设计:

CellStyle (单元格样式)
├── Font (字体)
├── Fill (填充)
├── Border (边框)
├── Alignment (对齐)
└── NumberFormat (数字格式)

快速开始

基础样式应用

from symphra_excel import Workbook, CellStyle
from symphra_excel.styles import Color

wb = Workbook()
sheet = wb.create_worksheet("样式示例")

# 创建样式
style = CellStyle()
style.set_font(name="微软雅黑", size=14, bold=True, color=Color.BLUE)
style.set_background_color(Color.LIGHT_YELLOW)

# 应用样式
sheet.set_cell_value("A1", "标题")
sheet.apply_style("A1", style)

wb.save("styled.xlsx")

样式组件

1. 字体样式 (Font)

控制文字的外观:

style = CellStyle()

# 字体属性
style.set_font(
    name="微软雅黑",      # 字体名称
    size=12,              # 字号
    bold=True,            # 粗体
    italic=False,         # 斜体
    underline="single",   # 下划线
    color=Color.BLUE      # 颜色
)

2. 填充样式 (Fill)

设置单元格背景:

style = CellStyle()

# 纯色填充
style.set_background_color(Color.LIGHT_BLUE)

# 图案填充
style.set_pattern_fill(
    pattern_type="solid",
    fg_color=Color.YELLOW,
    bg_color=Color.WHITE
)

3. 边框样式 (Border)

设置单元格边框:

from symphra_excel.styles import BorderStyle

style = CellStyle()

# 所有边框
style.set_border(BorderStyle.THIN, Color.BLACK)

# 单独设置每条边
style.set_border_side("top", BorderStyle.THICK, Color.RED)
style.set_border_side("bottom", BorderStyle.DOUBLE, Color.BLUE)
style.set_border_side("left", BorderStyle.THIN, Color.GREEN)
style.set_border_side("right", BorderStyle.DASHED, Color.ORANGE)

4. 对齐方式 (Alignment)

控制文字对齐:

style = CellStyle()

# 对齐设置
style.set_alignment(
    horizontal="center",   # 水平对齐: left, center, right
    vertical="middle",     # 垂直对齐: top, middle, bottom
    wrap_text=True,        # 自动换行
    shrink_to_fit=False,   # 缩小字体填充
    indent=0,              # 缩进级别
    text_rotation=0        # 文字旋转角度
)

5. 数字格式 (NumberFormat)

设置数字显示格式:

style = CellStyle()

# 常用格式
style.set_number_format("0.00")              # 两位小数
style.set_number_format("#,##0")             # 千分位
style.set_number_format("0.00%")             # 百分比
style.set_number_format("¥#,##0.00")         # 货币
style.set_number_format("yyyy-mm-dd")        # 日期
style.set_number_format("h:mm:ss")           # 时间

预定义样式

Symphra Excel提供了常用的预定义样式:

from symphra_excel.styles import PredefinedStyles

# 使用预定义样式
sheet.apply_style("A1", PredefinedStyles.header_style())      # 表头样式
sheet.apply_style("A2", PredefinedStyles.title_style())       # 标题样式
sheet.apply_style("A3", PredefinedStyles.subtitle_style())    # 副标题样式
sheet.apply_style("A4", PredefinedStyles.warning_style())     # 警告样式
sheet.apply_style("A5", PredefinedStyles.success_style())     # 成功样式
sheet.apply_style("A6", PredefinedStyles.error_style())       # 错误样式
sheet.apply_style("A7", PredefinedStyles.info_style())        # 信息样式

颜色系统

内置颜色

from symphra_excel.styles import Color

# 基本颜色
Color.BLACK
Color.WHITE
Color.RED
Color.GREEN
Color.BLUE
Color.YELLOW
Color.ORANGE
Color.PURPLE

# 浅色系
Color.LIGHT_RED
Color.LIGHT_GREEN
Color.LIGHT_BLUE
Color.LIGHT_YELLOW

# 深色系
Color.DARK_RED
Color.DARK_GREEN
Color.DARK_BLUE

自定义颜色

# RGB颜色
custom_color = Color.from_rgb(255, 128, 0)

# 十六进制颜色
hex_color = Color.from_hex("#FF8000")

样式复用

创建样式模板

# 创建可复用的样式
header_style = CellStyle()
header_style.set_font(name="微软雅黑", size=14, bold=True, color=Color.WHITE)
header_style.set_background_color(Color.DARK_BLUE)
header_style.set_alignment(horizontal="center", vertical="center")

# 应用到多个单元格
for cell in ["A1", "B1", "C1", "D1"]:
    sheet.apply_style(cell, header_style)

样式继承和修改

# 基础样式
base_style = CellStyle()
base_style.set_font(name="微软雅黑", size=12)

# 基于基础样式创建变体
title_style = base_style.copy()
title_style.set_font(size=16, bold=True)

subtitle_style = base_style.copy()
subtitle_style.set_font(size=14, italic=True)

批量样式应用

应用到范围

# 应用样式到单元格范围
for row in range(1, 11):  # 行1-10
    for col in range(1, 5):  # 列A-D
        cell = f"{chr(64+col)}{row}"
        sheet.apply_style(cell, style)

条件样式

# 根据值应用不同样式
for row in range(2, 100):
    value = sheet.get_cell_value(f"C{row}")

    if value > 10000:
        sheet.apply_style(f"C{row}", PredefinedStyles.success_style())
    elif value < 5000:
        sheet.apply_style(f"C{row}", PredefinedStyles.warning_style())

完整示例

示例1: 创建专业报表

from symphra_excel import Workbook, CellStyle
from symphra_excel.styles import Color, BorderStyle, PredefinedStyles

wb = Workbook()
sheet = wb.create_worksheet("销售报表")

# 标题样式
title_style = CellStyle()
title_style.set_font(name="微软雅黑", size=18, bold=True, color=Color.WHITE)
title_style.set_background_color(Color.DARK_BLUE)
title_style.set_alignment(horizontal="center", vertical="center")

# 表头样式
header_style = PredefinedStyles.header_style()

# 数据样式
data_style = CellStyle()
data_style.set_border(BorderStyle.THIN, Color.GRAY)
data_style.set_alignment(horizontal="left")

# 数字样式
number_style = CellStyle()
number_style.set_number_format("#,##0.00")
number_style.set_border(BorderStyle.THIN, Color.GRAY)
number_style.set_alignment(horizontal="right")

# 应用标题
sheet.set_cell_value("A1", "2024年度销售报表")
sheet.merge_cells("A1:D1")
sheet.apply_style("A1", title_style)

# 应用表头
headers = ["产品", "数量", "单价", "总额"]
for col_idx, header in enumerate(headers):
    cell = f"{chr(65+col_idx)}2"
    sheet.set_cell_value(cell, header)
    sheet.apply_style(cell, header_style)

# 应用数据
data = [
    ["iPhone 15", 100, 5999, 599900],
    ["MacBook Pro", 50, 12999, 649950],
    ["iPad Air", 80, 4599, 367920],
]

for row_idx, row_data in enumerate(data, start=3):
    # 产品名称
    sheet.set_cell_value(f"A{row_idx}", row_data[0])
    sheet.apply_style(f"A{row_idx}", data_style)

    # 数字列
    for col_idx in range(1, 4):
        cell = f"{chr(65+col_idx)}{row_idx}"
        sheet.set_cell_value(cell, row_data[col_idx])
        sheet.apply_style(cell, number_style)

wb.save("professional_report.xlsx")

示例2: 数据高亮

from symphra_excel import Workbook, CellStyle
from symphra_excel.styles import Color

wb = Workbook()
sheet = wb.create_worksheet("成绩单")

# 设置表头
headers = ["姓名", "数学", "英语", "总分"]
for col_idx, header in enumerate(headers):
    sheet.set_cell_value(f"{chr(65+col_idx)}1", header)

# 添加数据
students = [
    ["张三", 95, 88, 183],
    ["李四", 76, 82, 158],
    ["王五", 88, 91, 179],
    ["赵六", 62, 70, 132],
]

# 优秀/及格/不及格样式
excellent_style = CellStyle()
excellent_style.set_background_color(Color.LIGHT_GREEN)

good_style = CellStyle()
good_style.set_background_color(Color.LIGHT_YELLOW)

poor_style = CellStyle()
poor_style.set_background_color(Color.LIGHT_RED)

# 应用数据和条件样式
for row_idx, student in enumerate(students, start=2):
    for col_idx, value in enumerate(student):
        cell = f"{chr(65+col_idx)}{row_idx}"
        sheet.set_cell_value(cell, value)

        # 根据分数应用不同颜色
        if col_idx > 0:  # 只对分数列应用
            if value >= 90:
                sheet.apply_style(cell, excellent_style)
            elif value >= 60:
                sheet.apply_style(cell, good_style)
            else:
                sheet.apply_style(cell, poor_style)

wb.save("grades_highlighted.xlsx")

最佳实践

✅ 推荐做法

# 1. 创建样式模板,避免重复创建
header_style = PredefinedStyles.header_style()
for cell in headers:
    sheet.apply_style(cell, header_style)

# 2. 使用预定义样式
sheet.apply_style("A1", PredefinedStyles.title_style())

# 3. 样式复用和继承
base_style = CellStyle()
variant_style = base_style.copy()
variant_style.set_font(bold=True)

❌ 避免的做法

# 不要重复创建相同样式
for cell in cells:
    style = CellStyle()  # 每次都创建新对象
    style.set_font(bold=True)
    sheet.apply_style(cell, style)

# 不要过度使用样式
# 太多不同的样式会导致文件变大

下一步