Skip to content

Styles and formatting

Cell styles, conditional formats, tables and rich text.

API reference · Guide

Style dataclass

Style(fill: str | PatternFill | GradientFill | None = None, font_color: str | None = None, bold: bool | None = None, italic: bool | None = None, underline: bool | None = None, number_format: str | None = None, horizontal: str | None = None, vertical: str | None = None, wrap: bool | None = None, font: Font | None = None, pattern: PatternFill | None = None, border: Border | None = None, alignment: Alignment | None = None, protection: Protection | None = None, quote_prefix: bool | None = None, pivot_button: bool | None = None)

A reusable Excel cell style.

Colors are RGB hex strings ("008000" or "#008000"). None means “leave this property unchanged”, which also makes styles composable when a header style and a range style overlap.

The flat fields (fill, font_color, bold, italic, underline, number_format, horizontal, vertical, wrap) cover the legacy API; the structured fields (font, pattern, border, alignment, protection) are the openpyxl-like API. quote_prefix and pivot_button mirror openpyxl's flags on the cell format. fill accepts a color string (solid), PatternFill, or GradientFill. On conflict the structured object wins per property; a None sub-property falls back to the corresponding flat shorthand.

Examples:

A header style with a solid fill and a money format:

from xlspy import F, Style

header = Style(bold=True, fill="1F4E78", font_color="FFFFFF")
money = Style(number_format=F.THOUSANDS_SEP)
warn = Style(fill="FFF2CC", border=Border(bottom=Side("thin", "BF9000")))

Styles are composable because unset fields stay None; a range style only overrides the properties it sets.

See Also

Font, PatternFill, GradientFill, Border, Alignment and Protection for the structured properties, and DifferentialStyle for conditional formatting.

Font dataclass

Font(name: str | None = None, size: float | None = None, bold: bool | None = None, italic: bool | None = None, strike: bool | None = None, underline: str | bool | None = None, vertAlign: str | None = None, color: Color | str | None = None, charset: int | None = None, family: int | None = None, scheme: str | None = None, outline: bool | None = None, shadow: bool | None = None, condense: bool | None = None, extend: bool | None = None)

Bases: _Copyable

An openpyxl-like font. All-None means “no font override”.

Both the xlspy field names and openpyxl's spellings work: size/sz, bold/b, italic/i, underline/u and strike/strikethrough. copy(**changes) returns a modified copy.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

PatternFill dataclass

PatternFill(fill_type: str | None = None, start_color: Color | str | None = None, end_color: Color | str | None = None)

Bases: _Copyable

An openpyxl-like pattern fill. All-None means “no fill override”.

fill_type/patternType, start_color/fgColor and end_color/bgColor are interchangeable names.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

GradientFill dataclass

GradientFill(fill_type: str = 'linear', degree: float | None = None, left: float | None = None, right: float | None = None, top: float | None = None, bottom: float | None = None, stop: tuple[Stop | Color | str, ...] = ())

Bases: _Copyable

An openpyxl-like gradient fill (linear or path).

stop accepts Stop objects or plain colors; plain colors are spread evenly between position 0 and 1, matching openpyxl. type is the openpyxl spelling of fill_type.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

Stop dataclass

Stop(color: Color | str, position: float)

One gradient stop: a color at a position between 0 and 1.

Border dataclass

Border(left: Side | None = None, right: Side | None = None, top: Side | None = None, bottom: Side | None = None, diagonal: Side | None = None, diagonal_direction: str | None = None, vertical: Side | None = None, horizontal: Side | None = None, start: Side | None = None, end: Side | None = None, diagonal_up: bool | None = None, diagonal_down: bool | None = None, outline: bool | None = None)

Bases: _Copyable

An openpyxl-like border. All-None means “no border override”.

diagonalUp/diagonalDown are openpyxl's spellings of diagonal_up/diagonal_down.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

Side dataclass

Side(style: str | None = None, color: Color | str | None = None)

Bases: _Copyable

One border edge.

style accepts openpyxl's border_style spelling as well.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

Color dataclass

Color(rgb: str | None = None, indexed: int | None = None, theme: int | None = None, tint: float | None = None, auto: bool | None = None)

An Excel color: exactly one of rgb/indexed/theme/auto.

rgb accepts "RRGGBB" or "AARRGGBB" with or without "#" and is normalized to 8-char uppercase ARGB (FF alpha prefix when absent). auto=True requests the automatic (system) color.

Alignment dataclass

Alignment(horizontal: str | None = None, vertical: str | None = None, wrap_text: bool | None = None, shrink_to_fit: bool | None = None, indent: int | None = None, text_rotation: int | None = None, relative_indent: int | None = None, justify_last_line: bool | None = None, reading_order: int | None = None)

Bases: _Copyable

An openpyxl-like alignment. All-None means “no override”.

openpyxl's camelCase spellings (textRotation, wrapText, shrinkToFit, relativeIndent, justifyLastLine, readingOrder) are aliases of the snake_case fields.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

Protection dataclass

Protection(locked: bool | None = None, hidden: bool | None = None)

Bases: _Copyable

Cell protection flags. All-None means “no override”.

copy

copy(**changes: Any) -> Self

Return a copy of this object with the given fields replaced.

The keyword names are the field names; openpyxl's short spellings (sz, b, fgColor and so on) are accepted as well. Passing both spellings of one field raises TypeError, as the constructor does.

Source code in src/xlspy/styles/_attrs.py
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def copy(self, **changes: Any) -> Self:
    """Return a copy of this object with the given fields replaced.

    The keyword names are the field names; openpyxl's short spellings
    (``sz``, ``b``, ``fgColor`` and so on) are accepted as well. Passing
    both spellings of one field raises TypeError, as the constructor does.
    """
    for alias, name in self._ALIASES.items():
        if alias not in changes:
            continue
        value = changes.pop(alias)
        if name in changes:
            if changes[name] is not None and value is not None:
                raise TypeError(f"{type(self).__name__}.copy() got both {name!r} and its openpyxl alias {alias!r}")
            if changes[name] is not None:
                continue  # the long name wins, as in the constructor
        changes[name] = value
    values = {field.name: getattr(self, field.name) for field in fields(self)}  # type: ignore[arg-type]  # a frozen dataclass instance
    for key, value in changes.items():
        if key not in values:
            raise TypeError(f"{type(self).__name__}.copy() got an unexpected keyword argument {key!r}")
        values[key] = value
    return type(self)(**values)

DifferentialStyle dataclass

DifferentialStyle(font: Font | None = None, fill: PatternFill | GradientFill | None = None, border: Border | None = None, number_format: str | None = None, alignment: Alignment | None = None, protection: Protection | None = None)

The conditional-formatting style (openpyxl dxf).

Covers font, number format, fill (pattern or gradient), alignment, border, and protection — the same six components as openpyxl.

NamedStyle

NamedStyle(name: str = 'Normal', font: Font | None = None, fill: str | PatternFill | GradientFill | None = None, border: Border | None = None, alignment: Alignment | None = None, number_format: str | None = None, protection: Protection | None = None, builtinId: int | None = None, hidden: bool = False)

A cell style with a name: font, fill, border, alignment, number format and protection.

Register it with Workbook.add_named_style, then assign its name to cell.style.

Source code in src/xlspy/styles/named_styles.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def __init__(
    self,
    name: str = "Normal",
    font: Font | None = None,
    fill: str | PatternFill | GradientFill | None = None,
    border: Border | None = None,
    alignment: Alignment | None = None,
    number_format: str | None = None,
    protection: Protection | None = None,
    builtinId: int | None = None,
    hidden: bool = False,
) -> None:
    self.name = name
    self.font = font
    self.fill = fill
    self.border = border
    self.alignment = alignment
    self.number_format = number_format
    self.protection = protection
    self.builtinId = builtinId
    self.hidden = hidden

as_tuple

as_tuple() -> StyleArray

The style ids openpyxl keeps in its style array.

openpyxl returns a nine-id StyleArray in the order fontId, fillId, borderId, numFmtId, protectionId, alignmentId, pivotButton, quotePrefix, xfId. xlspy stores the components directly and assigns ids only while saving, so the array is all zeros, as openpyxl's is for a style not yet bound to a workbook. Read font, fill and the other components for their values.

Source code in src/xlspy/styles/named_styles.py
113
114
115
116
117
118
119
120
121
122
123
def as_tuple(self) -> StyleArray:
    """The style ids openpyxl keeps in its style array.

    openpyxl returns a nine-id ``StyleArray`` in the order ``fontId,
    fillId, borderId, numFmtId, protectionId, alignmentId, pivotButton,
    quotePrefix, xfId``. xlspy stores the components directly and assigns
    ids only while saving, so the array is all zeros, as openpyxl's is for
    a style not yet bound to a workbook. Read ``font``, ``fill`` and the
    other components for their values.
    """
    return StyleArray()

NamedStyleList

Bases: list['str | NamedStyle']

names property

names: list[str]

The style names, in order.

add

add(style: str | NamedStyle) -> None

Add a style, replacing one with the same name.

Source code in src/xlspy/styles/named_styles.py
135
136
137
138
139
def add(self, style: str | NamedStyle) -> None:
    """Add a style, replacing one with the same name."""
    name = style if isinstance(style, str) else style.name
    self[:] = [item for item in self if (item if isinstance(item, str) else item.name) != name]
    self.append(style)

keys

keys() -> list[str]

The style names, as a dict-like view over the list.

Source code in src/xlspy/styles/named_styles.py
141
142
143
def keys(self) -> list[str]:
    """The style names, as a dict-like view over the list."""
    return self.names

values

values() -> list[str | NamedStyle]

The styles, as a dict-like view over the list.

Source code in src/xlspy/styles/named_styles.py
145
146
147
def values(self) -> list[str | NamedStyle]:
    """The styles, as a dict-like view over the list."""
    return list(self)

items

items() -> list[tuple[str, str | NamedStyle]]

The names and their styles, as a dict-like view over the list.

Source code in src/xlspy/styles/named_styles.py
149
150
151
def items(self) -> list[tuple[str, str | NamedStyle]]:
    """The names and their styles, as a dict-like view over the list."""
    return [(name, style) for name, style in zip(self.names, self)]

get

get(name: str, default: object = None) -> object

The style called name, or default when there is none.

Source code in src/xlspy/styles/named_styles.py
153
154
155
156
157
158
def get(self, name: str, default: object = None) -> object:
    """The style called ``name``, or ``default`` when there is none."""
    for item in self:
        if (item if isinstance(item, str) else item.name) == name:
            return item
    return default

ExcelTable dataclass

ExcelTable(display_name: str, ref: str, columns: list[str] | tuple[str, ...] | None = None, header_row: bool = True, totals_row: bool = False, style_name: str = 'TableStyleMedium9', show_first_column: bool = False, show_last_column: bool = False, show_row_stripes: bool = True, show_column_stripes: bool = False, totals_row_functions: tuple[str | None, ...] | None = None)

An Excel table (ListObject) bound to a rectangular range.

The range must have a header row whose cells match the column names. Table names must be unique in the workbook and may not read as a cell reference (T1, AB12).

Examples:

Turn written rows into a filterable, styled table:

from xlspy import ExcelTable, XlsxWriter

rows = [["Region", "Sales"], ["North", 120], ["South", 90]]
sales = ExcelTable("Sales", "A1:B3", style_name="TableStyleMedium2")

with XlsxWriter("table.xlsx") as workbook:
    workbook.add_sheet("Data")
    workbook.write_sheet(rows, tables=[sales], auto_filter=True)

A totals row uses the last row of the range:

ExcelTable("Sales", "A1:B4", totals_row=True,
           totals_row_functions=(None, "sum"))
See Also

PivotTable to summarise a table, and Slicer to filter one.

CellIsRule dataclass

CellIsRule(sqref: str, operator: str, formula: list[str] | tuple[str, ...] | str, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

A cellIs conditional-formatting rule.

FormulaRule dataclass

FormulaRule(sqref: str, formula: list[str] | tuple[str, ...] | str, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

An expression conditional-formatting rule.

ColorScaleRule dataclass

ColorScaleRule(sqref: str, minimum: FormatObject | None, midpoint: FormatObject | None, maximum: FormatObject | None, colors: list[Color | str] | tuple[Color | str, ...], priority: int | None = None)

A 2-color (midpoint None) or 3-color scale rule.

DataBarRule dataclass

DataBarRule(sqref: str, minimum: FormatObject | None, maximum: FormatObject | None, color: Color | str, show_value: bool | None = None, min_length: int | None = None, max_length: int | None = None, priority: int | None = None)

A dataBar conditional-formatting rule.

IconSetRule dataclass

IconSetRule(sqref: str, icon_style: str, values: list[float | str] | tuple[float | str, ...], cfvo_type: str = 'percent', show_value: bool | None = None, percent: bool | None = None, reverse: bool | None = None, stop_if_true: bool | None = None, priority: int | None = None, *, type: str | None = None)

An iconSet conditional-formatting rule (openpyxl-like).

cfvo_type is the type of the thresholds in values; type is the rule type, "iconSet", as in openpyxl.

Source code in src/xlspy/styles/_cf_rules.py
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def __init__(
    self,
    sqref: str,
    icon_style: str,
    values: list[float | str] | tuple[float | str, ...],
    cfvo_type: str = "percent",
    show_value: bool | None = None,
    percent: bool | None = None,
    reverse: bool | None = None,
    stop_if_true: bool | None = None,
    priority: int | None = None,
    *,
    type: str | None = None,
) -> None:
    if type is not None and type != "iconSet":
        warnings.warn(
            "IconSetRule(type=...) is deprecated; pass cfvo_type= "
            "(type is the rule type, 'iconSet', as in openpyxl)",
            DeprecationWarning,
            stacklevel=2,
        )
        cfvo_type = type
    for name, value in (
        ("sqref", sqref),
        ("icon_style", icon_style),
        ("values", values),
        ("cfvo_type", cfvo_type),
        ("show_value", show_value),
        ("percent", percent),
        ("reverse", reverse),
        ("stop_if_true", stop_if_true),
        ("priority", priority),
    ):
        object.__setattr__(self, name, value)
    self.__post_init__()

FormatObject dataclass

FormatObject(type: str, value: str | float | None = None)

A cfvo data-bar / color-scale endpoint.

TopBottomRule dataclass

TopBottomRule(sqref: str, rank: int = 10, percent: bool = False, bottom: bool = False, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Top or bottom rank values (percent=True: rank percent) (XLSX).

AboveAverageRule dataclass

AboveAverageRule(sqref: str, below: bool = False, equal_average: bool = False, std_dev: int | None = None, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Values above (or below) the range's average; std_dev moves the threshold by that many standard deviations (XLSX).

TextRule dataclass

TextRule(sqref: str, operator: str, text: str, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Cells whose text contains, notContains, beginsWith or endsWith text (case-insensitive, as in Excel) (XLSX).

DuplicateRule dataclass

DuplicateRule(sqref: str, unique: bool = False, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Duplicate values in the range, or unique=True for values that occur once (XLSX).

TimePeriodRule dataclass

TimePeriodRule(sqref: str, period: str, dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Dates in a period relative to today, such as "last7Days" (XLSX).

BlanksRule dataclass

BlanksRule(sqref: str, kind: str = 'blanks', dxf: DifferentialStyle | None = None, stop_if_true: bool | None = None, priority: int | None = None)

Blank ("blanks"/"no_blanks") or error ("errors"/"no_errors") cells (XLSX).

CellRichText

CellRichText(*args: Any)

Bases: list['str | TextBlock']

A cell value made of plain strings and TextBlock runs.

Examples:

Mix plain text with a bold run:

from xlspy import CellRichText, InlineFont, TextBlock, XlsxWriter

value = CellRichText(
    "Revenue: ",
    TextBlock(InlineFont(b=True, color="1F4E78"), "12,500"),
)
with XlsxWriter("rich.xlsx") as workbook:
    workbook.add_sheet("Data")
    workbook.write_sheet([["Label"], [value]])

A list or tuple of parts is accepted too, and rich text works in both XLSX and XLSB.

See Also

TextBlock and InlineFont for the run properties.

Source code in src/xlspy/rich_text.py
133
134
135
136
137
def __init__(self, *args: Any) -> None:
    parts = args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args
    super().__init__()
    for part in parts:
        self.append(part)

append

append(part: str | TextBlock) -> None

Add a part: a str or a TextBlock.

Source code in src/xlspy/rich_text.py
139
140
141
142
143
def append(self, part: str | TextBlock) -> None:
    """Add a part: a str or a TextBlock."""
    if not isinstance(part, (str, TextBlock)):
        raise TypeError("CellRichText parts must be str or TextBlock")
    super().append(part)

extend

extend(parts: Iterable[str | TextBlock]) -> None

Add several parts.

Source code in src/xlspy/rich_text.py
145
146
147
148
def extend(self, parts: Iterable[str | TextBlock]) -> None:
    """Add several parts."""
    for part in parts:
        self.append(part)

as_list

as_list() -> list[str]

The parts as plain strings, without their formatting.

Source code in src/xlspy/rich_text.py
156
157
158
def as_list(self) -> list[str]:
    """The parts as plain strings, without their formatting."""
    return [str(part) for part in self]

runs_xml

runs_xml(prefix: str = '') -> str

The <r> runs for an <si> or <is> element.

Source code in src/xlspy/rich_text.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
def runs_xml(self, prefix: str = "") -> str:
    """The ``<r>`` runs for an ``<si>`` or ``<is>`` element."""
    check_cell_text(str(self))
    runs = []
    for part in self:
        if isinstance(part, TextBlock):
            font, text = part.font._xml(prefix), part.text
        else:
            font, text = "", part
        if not text:
            continue
        space = ' xml:space="preserve"' if text != text.strip() else ""
        runs.append(f"<{prefix}r>{font}<{prefix}t{space}>{xstring_escape(escape(text))}</{prefix}t></{prefix}r>")
    return "".join(runs) or f"<{prefix}t/>"

TextBlock dataclass

TextBlock(font: InlineFont, text: str)

A run of text in font.

InlineFont dataclass

InlineFont(rFont: str | None = None, b: bool | None = None, i: bool | None = None, u: str | None = None, strike: bool | None = None, sz: float | None = None, color: Color | str | None = None, vertAlign: str | None = None, family: int | None = None, charset: int | None = None, scheme: str | None = None, outline: bool | None = None, shadow: bool | None = None, condense: bool | None = None, extend: bool | None = None)

The font of one run, with openpyxl's names: b bold, i italic, u underline ("single", "double", ...), strike, sz size in points, color ("RRGGBB" or a Color), rFont font name, vertAlign ("superscript"/"subscript").