Excel operators¶
commons.excel_operators
¶
Classes:
| Name | Description |
|---|---|
ExcelTheme |
Theme configuration for Excel spreadsheet styling. |
ExcelCellFormat |
Cell formatting configuration for Excel cells. |
ExcelColumn |
Configuration for an Excel column. |
ExcelWriter |
Writer for creating formatted Excel spreadsheets. |
Attributes:
| Name | Type | Description |
|---|---|---|
T |
|
ExcelTheme
¶
Bases: TypedDict
Theme configuration for Excel spreadsheet styling.
Defines color scheme for various UI elements including primary colors, accent colors, neutral tones, and status indicators.
Attributes:
| Name | Type | Description |
|---|---|---|
primary_bg_color |
str
|
Primary background color (hex format) |
primary_color |
str
|
Primary text/foreground color (hex format) |
accent_1_bg_color |
str
|
First accent background color (hex format) |
accent_1_color |
str
|
First accent text/foreground color (hex format) |
accent_2_bg_color |
str
|
Second accent background color (hex format) |
accent_2_color |
str
|
Second accent text/foreground color (hex format) |
neutral_dark |
str
|
Dark neutral color (hex format) |
neutral_mid |
str
|
Medium neutral color (hex format) |
neutral_light |
str
|
Light neutral color (hex format) |
positive |
str
|
Positive status indicator color (hex format) |
caution |
str
|
Caution/warning status indicator color (hex format) |
negative |
str
|
Negative/error status indicator color (hex format) |
ExcelCellFormat
¶
Bases: TypedDict
Cell formatting configuration for Excel cells.
All fields are optional (total=False). Used to customize the appearance of cells including alignment, colors, borders, and text wrapping.
Attributes:
| Name | Type | Description |
|---|---|---|
align |
Literal['left', 'center', 'right']
|
Horizontal text alignment ("left", "center", or "right") |
bg_color |
str
|
Background color (hex format) |
bold |
bool
|
Whether text should be bold |
border |
int
|
Border width for all sides (integer value) |
bottom |
int
|
Bottom border width (integer value) |
color |
str
|
Text/foreground color (hex format) |
left |
int
|
Left border width (integer value) |
right |
int
|
Right border width (integer value) |
text_wrap |
bool
|
Whether text should wrap within the cell |
top |
int
|
Top border width (integer value) |
valign |
Literal['top', 'center', 'bottom']
|
Vertical text alignment ("top", "center", or "bottom") |
ExcelColumn
dataclass
¶
ExcelColumn(
name: str,
title: Optional[str] = None,
width: Optional[int] = 40,
hidden: bool = False,
format: Optional[
Callable[
[ExcelTheme, ExcelCellFormat], ExcelCellFormat
]
] = None,
header_format: Optional[
Callable[
[ExcelTheme, ExcelCellFormat], ExcelCellFormat
]
] = None,
modify_cell: Optional[
Callable[
[ExcelTheme, Workbook, Worksheet, int, int],
None,
]
] = None,
)
Configuration for an Excel column.
Defines the properties and formatting for a single column in an Excel worksheet, including name, display title, width, and custom formatting functions.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Column name (used to reference data in DataFrame) |
title |
Optional[str]
|
Display title for column header (defaults to name if not provided) |
width |
Optional[int]
|
Column width in character units (default: 40) |
format |
Optional[Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]]
|
Optional function to customize cell format. Takes (theme, base_format) and returns modified ExcelCellFormat |
header_format |
Optional[Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]]
|
Optional function to customize header cell format. Takes (theme, base_format) and returns modified ExcelCellFormat |
modify_cell |
Optional[Callable[[ExcelTheme, Workbook, Worksheet, int, int], None]]
|
Optional callback for advanced cell modification. Takes (theme, workbook, worksheet, column_index, row_count) and allows direct manipulation of cells in the column |
format
class-attribute
instance-attribute
¶
format: Optional[
Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]
] = None
header_format
class-attribute
instance-attribute
¶
header_format: Optional[
Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]
] = None
modify_cell
class-attribute
instance-attribute
¶
modify_cell: Optional[
Callable[
[ExcelTheme, Workbook, Worksheet, int, int], None
]
] = None
ExcelWriter
¶
ExcelWriter(
header_format: ExcelCellFormat,
std_cell_format: ExcelCellFormat,
theme: ExcelTheme,
)
Writer for creating formatted Excel spreadsheets.
Provides high-level API for creating Excel files from pandas DataFrames or Python objects with consistent formatting, theming, and styling.
Type Aliases:
| Name | Description |
|---|---|
CellFormat |
Alias for ExcelCellFormat |
Column |
Alias for ExcelColumn |
Theme |
Alias for ExcelTheme |
Usage
writer = ExcelWriter.create() writer.write_excel_from_df(df, Path("output.xlsx"), columns)
Initialize ExcelWriter with formatting configuration.
Note: Direct instantiation is discouraged. Use ExcelWriter.create() factory method instead for default configurations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
header_format
|
ExcelCellFormat
|
Format configuration for header cells |
required |
std_cell_format
|
ExcelCellFormat
|
Format configuration for standard data cells |
required |
theme
|
ExcelTheme
|
Color theme for styling |
required |
Classes:
| Name | Description |
|---|---|
StandardFormats |
Collection of standard cell format presets. |
Methods:
| Name | Description |
|---|---|
create |
Create an ExcelWriter instance with optional custom configuration. |
write_excel_from_df |
Write a pandas DataFrame to an Excel file with formatting. |
write_excel_from_objects |
Write a list of Python objects to an Excel file with formatting. |
write_excel_multi_sheet |
Write multiple sheets to an Excel file with formatting. |
Attributes:
| Name | Type | Description |
|---|---|---|
CellFormat |
|
|
Column |
|
|
Theme |
|
|
Workbook |
|
|
Worksheet |
|
|
header_format |
|
|
std_cell_format |
|
|
theme |
|
Source code in src/commons/excel_operators.py
StandardFormats
¶
Collection of standard cell format presets.
Provides commonly used border format configurations. Border widths: - 1: Thin border - 2: Medium border
Attributes:
| Name | Type | Description |
|---|---|---|
border_bottom_thin |
ExcelCellFormat
|
Thin bottom border (width 1) |
border_bottom_medium |
ExcelCellFormat
|
Medium bottom border (width 2) |
border_left_thin |
ExcelCellFormat
|
Thin left border (width 1) |
border_left_medium |
ExcelCellFormat
|
Medium left border (width 2) |
border_right_thin |
ExcelCellFormat
|
Thin right border (width 1) |
border_right_medium |
ExcelCellFormat
|
Medium right border (width 2) |
border_top_thin |
ExcelCellFormat
|
Thin top border (width 1) |
border_top_medium |
ExcelCellFormat
|
Medium top border (width 2) |
border_bottom_thin
class-attribute
instance-attribute
¶
border_bottom_thin: ExcelCellFormat = {'bottom': 1}
border_bottom_medium
class-attribute
instance-attribute
¶
border_bottom_medium: ExcelCellFormat = {'bottom': 2}
border_left_thin
class-attribute
instance-attribute
¶
border_left_thin: ExcelCellFormat = {'left': 1}
border_left_medium
class-attribute
instance-attribute
¶
border_left_medium: ExcelCellFormat = {'left': 2}
border_right_thin
class-attribute
instance-attribute
¶
border_right_thin: ExcelCellFormat = {'right': 1}
border_right_medium
class-attribute
instance-attribute
¶
border_right_medium: ExcelCellFormat = {'right': 2}
border_top_medium
class-attribute
instance-attribute
¶
border_top_medium: ExcelCellFormat = {'top': 2}
create
staticmethod
¶
create(
theme: Optional[ExcelTheme] = None,
header_format_factory: Optional[
Callable[
[ExcelTheme, ExcelCellFormat], ExcelCellFormat
]
] = None,
std_cell_format_factory: Optional[
Callable[
[ExcelTheme, ExcelCellFormat], ExcelCellFormat
]
] = None,
) -> ExcelWriter
Create an ExcelWriter instance with optional custom configuration.
Factory method that provides sensible defaults for theme and formatting. If no theme is provided, uses a blue-based professional color scheme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
Optional[ExcelTheme]
|
Optional custom color theme. If None, uses default blue theme with primary color #00338D (deep blue) and complementary accents |
None
|
header_format_factory
|
Optional[Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]]
|
Optional function to customize header format. Takes (theme, default_header_format) and returns modified format. Default header format includes: bold text, text wrap, top alignment, left alignment, primary theme colors, and medium bottom border |
None
|
std_cell_format_factory
|
Optional[Callable[[ExcelTheme, ExcelCellFormat], ExcelCellFormat]]
|
Optional function to customize standard cell format. Takes (theme, default_cell_format) and returns modified format. Default cell format includes: top alignment and text wrap |
None
|
Returns:
| Type | Description |
|---|---|
ExcelWriter
|
Configured ExcelWriter instance ready to write Excel files |
Example
Use defaults¶
writer = ExcelWriter.create()
Custom theme¶
custom_theme = {"primary_bg_color": "#FF0000", ...} writer = ExcelWriter.create(theme=custom_theme)
Custom formatting¶
def my_header_fmt(theme, base_fmt): return {**base_fmt, "align": "center"} writer = ExcelWriter.create(header_format_factory=my_header_fmt)
Source code in src/commons/excel_operators.py
write_excel_from_df
¶
write_excel_from_df(
df: DataFrame,
path: Union[Path, BinaryIO],
columns: Optional[List[ExcelColumn]] = None,
sheet_name: str = "Sheet 1",
sheet_fomatter: Optional[
Callable[
[
Workbook,
Worksheet,
List[ExcelColumn],
DataFrame,
],
None,
]
] = None,
) -> None
Write a pandas DataFrame to an Excel file with formatting.
Creates an Excel workbook at the specified path with the DataFrame data. Automatically applies formatting, column widths, freeze panes, and autofilters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
pandas DataFrame to write to Excel |
required |
path
|
Union[Path, BinaryIO]
|
File path where Excel file should be written |
required |
columns
|
Optional[List[ExcelColumn]]
|
Optional list of ExcelColumn configurations. If None, creates default columns from df.columns with standard formatting |
None
|
sheet_name
|
str
|
Name of the worksheet (default: "Sheet 1") |
'Sheet 1'
|
sheet_fomatter
|
Optional[Callable[[Workbook, Worksheet, List[ExcelColumn], DataFrame], None]]
|
Optional callback for advanced worksheet customization. Takes (worksheet, workbook, columns, dataframe) for post-processing |
None
|
Features
- Applies custom column widths and formatting
- Freezes top header row
- Adds autofilter to all columns
- Uses theme colors for headers
- Supports per-column format customization
Example
columns = [ ExcelColumn("name", width=30), ExcelColumn("email", width=40), ] writer.write_excel_from_df(df, Path("output.xlsx"), columns)
Source code in src/commons/excel_operators.py
write_excel_from_objects
¶
write_excel_from_objects(
items: List[T],
items_to_dict: Callable[[T], dict],
path: Union[Path, BinaryIO],
columns: List[ExcelColumn],
sheet_name: str = "Sheet 1",
sheet_fomatter: Optional[
Callable[
[
Workbook,
Worksheet,
List[ExcelColumn],
DataFrame,
],
None,
]
] = None,
) -> None
Write a list of Python objects to an Excel file with formatting.
Converts objects to dictionaries, then to DataFrame, and writes to Excel. Provides a convenient interface for writing domain objects or dataclasses to Excel without manual DataFrame conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
List[T]
|
List of objects to write to Excel |
required |
items_to_dict
|
Callable[[T], dict]
|
Function that converts each object to a dictionary. Dictionary keys should match column names |
required |
path
|
Union[Path, BinaryIO]
|
File path where Excel file should be written |
required |
columns
|
List[ExcelColumn]
|
List of ExcelColumn configurations defining column order, widths, and formatting |
required |
sheet_name
|
str
|
Name of the worksheet (default: "Sheet 1") |
'Sheet 1'
|
sheet_fomatter
|
Optional[Callable[[Workbook, Worksheet, List[ExcelColumn], DataFrame], None]]
|
Optional callback for advanced worksheet customization. Takes (worksheet, workbook, columns, dataframe) for post-processing |
None
|
Note
If items list is empty, creates an Excel file with headers only.
Example
@dataclass class Person: name: str age: int
people = [Person("Alice", 30), Person("Bob", 25)] columns = [ ExcelColumn("name", width=30), ExcelColumn("age", width=10), ]
def person_to_dict(p: Person) -> dict: return {"name": p.name, "age": p.age}
writer.write_excel_from_objects( people, person_to_dict, Path("people.xlsx"), columns )
Source code in src/commons/excel_operators.py
write_excel_multi_sheet
¶
write_excel_multi_sheet(
sheets: List[tuple[str, DataFrame, List[ExcelColumn]]],
path: Union[Path, BinaryIO],
) -> None
Write multiple sheets to an Excel file with formatting.
Creates an Excel workbook with multiple worksheets, each with its own DataFrame and column configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sheets
|
List[tuple[str, DataFrame, List[ExcelColumn]]]
|
List of tuples, each containing: - sheet_name: Name of the worksheet - df: pandas DataFrame to write - columns: List of ExcelColumn configurations |
required |
path
|
Union[Path, BinaryIO]
|
File path where Excel file should be written |
required |
Example
sheets = [ ("Users", users_df, user_columns), ("Orders", orders_df, order_columns), ] writer.write_excel_multi_sheet(sheets, Path("output.xlsx"))