Excel
rn_forge.data.excel
Excel workbook, formatting, and tabular export helpers built on openpyxl.
CellFormat(font=None, fill=None, border=None, number_format=None, alignment=None, protection=None)
dataclass
Bases: DataclassMixin
Cell formatting attributes applied via :meth:ExcelUtils.format_row.
All fields are optional; only non-None values are applied to cells.
__repr__()
Return an unambiguous ClassName(field=value, ...) representation.
Excluded fields (metadata={"exclude": True}) are omitted. Falls
back to :func:object.__repr__ when the class is not a dataclass.
Returns:
| Type | Description |
|---|---|
str
|
A string of the form |
__str__()
Return a JSON string representation of this instance.
Equivalent to calling :meth:to_json. Excluded fields are omitted.
Returns:
| Type | Description |
|---|---|
str
|
A compact JSON string (no indentation). |
as_dict(*, exclude_hidden=True)
Convert this dataclass instance to a plain dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_hidden
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict mapping field names to their current values. Nested |
dict[str, Any]
|
dataclasses are recursively converted, respecting |
dict[str, Any]
|
metadata at every level. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the subclass was not decorated with
|
from_dict(data)
classmethod
Create an instance from a dict, recursively rebuilding nested dataclasses.
Only keys that match declared dataclass field names are passed to the
constructor. This makes from_dict tolerant of extra data (e.g.
when loading from a config file that has fields added in a newer
schema version). Nested dataclass-typed fields are reconstructed
recursively for common container annotations, via :mod:dacite.
Note a nested dataclass field's own overridden from_dict (if any)
is not called — dacite structures nested dataclasses itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
A dict whose keys correspond to dataclass field names.
Unrecognised keys are silently ignored, or rejected when the
class's |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance of this class populated with matching field values. |
Raises:
| Type | Description |
|---|---|
AppException
|
A value does not match its field's declared type, a
required field is absent, or an enum-typed field names a member
the enum does not define. Under |
TypeError
|
If the subclass was not decorated with
|
from_json(text)
classmethod
Create an instance from a JSON string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A JSON string representing a dict of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed JSON. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If text is not valid JSON. |
from_yaml(text)
classmethod
Create an instance from a YAML string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A YAML string representing a mapping of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed YAML. |
Raises:
| Type | Description |
|---|---|
YAMLError
|
If text is not valid YAML. |
to_json(*, indent=None, **kwargs)
Serialise this instance to a JSON string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indent
|
str | int | None
|
Indentation level passed to :func: |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:func: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A JSON string representation of this instance. |
to_yaml(**kwargs)
Serialise this instance to a YAML string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:meth: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A YAML string representation of this instance. |
ExcelUtils
Excel workbook operations via openpyxl.
Requires openpyxl — install with rn-forge-data.
Typical workflow::
wb = ExcelUtils.new_workbook()
sheet = wb.active
sheet.title = "Orders"
sheet.append(["id", "total"])
sheet.append([1001, 42.50])
ExcelUtils.write_workbook(wb, "build/orders.xlsx")
add_table(sheet, table_name, cell_range, style, show_first_column=None, show_last_column=None, show_row_stripes=None, show_column_stripes=None)
staticmethod
Add a named table to sheet.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sheet
|
Worksheet
|
Target worksheet. |
required |
table_name
|
str
|
Unique display name for the table (e.g. |
required |
cell_range
|
str
|
Excel range reference (e.g. |
required |
style
|
str
|
Table style name (e.g. |
required |
show_first_column
|
bool | None
|
Optional table style flags. |
None
|
auto_adjust_column_width(sheet)
staticmethod
Set each column's width to fit the longest cell value in that column.
column_letter(column_number)
staticmethod
Convert a 1-based column number to its Excel letter(s).
Examples: 1 → "A", 26 → "Z", 27 → "AA".
format_row(row, row_format=None, column_formats=None)
staticmethod
Apply row_format and per-column column_formats to every cell in row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
tuple[Any, ...]
|
Tuple of |
required |
row_format
|
CellFormat | None
|
Format applied to every cell in the row before column overrides. |
None
|
column_formats
|
dict[int, CellFormat] | None
|
Mapping of 1-based column index → :class: |
None
|
load_workbook(source, read_only=False, keep_vba=False, data_only=False, keep_links=True, rich_text=False)
staticmethod
Load an existing Excel file from a path or byte stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | BytesIO
|
File path or :class: |
required |
read_only
|
bool
|
Open in read-only mode (faster for large files). |
False
|
keep_vba
|
bool
|
Preserve VBA macros. |
False
|
data_only
|
bool
|
Return cell values instead of formulae. |
False
|
keep_links
|
bool
|
Preserve external links. |
True
|
rich_text
|
bool
|
Preserve rich-text cell content. |
False
|
new_workbook(write_only=False, iso_dates=False)
staticmethod
Create and return a new blank :class:~openpyxl.workbook.Workbook.
resize_table(sheet, table_name)
staticmethod
Resize the named table to span all rows currently in sheet.
Updates the table's ref to A1:<last-column><last-row>.
Raises:
| Type | Description |
|---|---|
TypeError
|
If the last cell in the final row is a merged cell (no column letter). |
write_workbook(workbook, path)
staticmethod
Save workbook to path, creating parent directories as needed.
Returns the resolved :class:~pathlib.Path written.
write_workbook_bytes(workbook)
staticmethod
Serialise workbook to an in-memory :class:~io.BytesIO buffer.
WorkbookTemplate(name, columns, row_format=None, column_formats=dict[int, CellFormat]())
dataclass
Bases: DataclassMixin
Configuration struct for a worksheet's column layout and default formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Sheet name. |
required |
columns
|
list[str]
|
Ordered list of column header strings. |
required |
row_format
|
CellFormat | None
|
Default :class: |
None
|
column_formats
|
dict[int, CellFormat]
|
Per-column format overrides keyed by 1-based column index. |
dict[int, CellFormat]()
|
__repr__()
Return an unambiguous ClassName(field=value, ...) representation.
Excluded fields (metadata={"exclude": True}) are omitted. Falls
back to :func:object.__repr__ when the class is not a dataclass.
Returns:
| Type | Description |
|---|---|
str
|
A string of the form |
__str__()
Return a JSON string representation of this instance.
Equivalent to calling :meth:to_json. Excluded fields are omitted.
Returns:
| Type | Description |
|---|---|
str
|
A compact JSON string (no indentation). |
as_dict(*, exclude_hidden=True)
Convert this dataclass instance to a plain dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude_hidden
|
bool
|
When |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A dict mapping field names to their current values. Nested |
dict[str, Any]
|
dataclasses are recursively converted, respecting |
dict[str, Any]
|
metadata at every level. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the subclass was not decorated with
|
from_dict(data)
classmethod
Create an instance from a dict, recursively rebuilding nested dataclasses.
Only keys that match declared dataclass field names are passed to the
constructor. This makes from_dict tolerant of extra data (e.g.
when loading from a config file that has fields added in a newer
schema version). Nested dataclass-typed fields are reconstructed
recursively for common container annotations, via :mod:dacite.
Note a nested dataclass field's own overridden from_dict (if any)
is not called — dacite structures nested dataclasses itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
A dict whose keys correspond to dataclass field names.
Unrecognised keys are silently ignored, or rejected when the
class's |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance of this class populated with matching field values. |
Raises:
| Type | Description |
|---|---|
AppException
|
A value does not match its field's declared type, a
required field is absent, or an enum-typed field names a member
the enum does not define. Under |
TypeError
|
If the subclass was not decorated with
|
from_json(text)
classmethod
Create an instance from a JSON string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A JSON string representing a dict of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed JSON. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If text is not valid JSON. |
from_yaml(text)
classmethod
Create an instance from a YAML string.
Delegates to :meth:from_dict after parsing, so unknown keys are
ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
A YAML string representing a mapping of field values. |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A new instance populated from the parsed YAML. |
Raises:
| Type | Description |
|---|---|
YAMLError
|
If text is not valid YAML. |
to_json(*, indent=None, **kwargs)
Serialise this instance to a JSON string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indent
|
str | int | None
|
Indentation level passed to :func: |
None
|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:func: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A JSON string representation of this instance. |
to_yaml(**kwargs)
Serialise this instance to a YAML string.
Fields excluded via metadata={"exclude": True} are omitted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Any
|
Additional keyword arguments forwarded to
:meth: |
{}
|
Returns:
| Type | Description |
|---|---|
str
|
A YAML string representation of this instance. |
write_xlsx(dataset, column_formats=None, sheet_title='Sheet1')
Serialise dataset to .xlsx bytes, with per-column number formats.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset
|
Data to write. Its headers form the first row; without headers only data rows are written. |
required |
column_formats
|
Mapping[str, str] | None
|
Excel number format per header name, for example
|
None
|
sheet_title
|
str
|
Worksheet title. |
'Sheet1'
|
Returns:
| Type | Description |
|---|---|
bytes
|
The workbook as bytes. |
Raises:
| Type | Description |
|---|---|
KeyError
|
A column_formats key is not a dataset header. |