Skip to content

excel_exporter

excel_exporter

Excel export functionality for scenario data.

Classes

PathManager

Handles file path operations for Excel export.

Functions
ensure_directory_exists staticmethod
ensure_directory_exists(path)

Create parent directory if it doesn't exist.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def ensure_directory_exists(path: str) -> None:
    """Create parent directory if it doesn't exist."""
    try:
        Path(path).parent.mkdir(parents=True, exist_ok=True)
    except (PermissionError, OSError) as e:
        logger.warning("Could not create directory for %s: %s", path, e)
get_hourly_curves_path staticmethod
get_hourly_curves_path(main_path)

Get path for hourly curves workbook.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def get_hourly_curves_path(main_path: Path) -> Path:
    """Get path for hourly curves workbook."""
    return main_path.with_name(
        f"{main_path.stem}_hourly_output_curves{main_path.suffix}"
    )
get_annual_exports_path staticmethod
get_annual_exports_path(main_path)

Get path for annual exports workbook.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def get_annual_exports_path(main_path: Path) -> Path:
    """Get path for annual exports workbook."""
    return main_path.with_name(f"{main_path.stem}_annual_exports{main_path.suffix}")

MainSheetWriter

Writes main scenario info sheet to Excel.

Functions
write staticmethod
write(workbook, main_info, scenarios)

Write main scenario information sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write(
    workbook: Workbook, main_info: pd.DataFrame, scenarios: list[Any]
) -> None:
    """Write main scenario information sheet."""
    if main_info.empty:
        return

    excel_main_df = excel_utils.build_excel_main_dataframe(main_info, scenarios)
    sanitized_df = excel_utils.sanitize_dataframe_for_excel(excel_main_df)
    excel_utils.add_frame(
        name="MAIN",
        frame=sanitized_df,
        workbook=workbook,
        column_width=18,
        scenario_styling=True,
        row_based_scenarios=True,
    )

DataSheetWriter

Writes data sheets (inputs, sortables, etc.) to Excel.

Functions
write_inputs staticmethod
write_inputs(workbook, inputs)

Write inputs sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_inputs(workbook: Workbook, inputs: Optional[pd.DataFrame]) -> None:
    """Write inputs sheet."""
    if inputs is None or inputs.empty:
        return
    excel_utils.add_frame("SLIDER_SETTINGS", inputs, workbook, column_width=18)
write_inputs_detailed staticmethod
write_inputs_detailed(workbook, inputs_detailed)

Write detailed inputs sheet with defaults and min/max.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_inputs_detailed(
    workbook: Workbook, inputs_detailed: Optional[pd.DataFrame]
) -> None:
    """Write detailed inputs sheet with defaults and min/max."""
    if inputs_detailed is None or inputs_detailed.empty:
        return

    sanitized = inputs_detailed.map(
        lambda v: ", ".join(map(str, v)) if isinstance(v, (list, tuple, set)) else v
    )
    excel_utils.add_frame("INPUT_DETAILS", sanitized, workbook, column_width=18)
write_sortables staticmethod
write_sortables(workbook, sortables)

Write sortables sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_sortables(workbook: Workbook, sortables: Optional[pd.DataFrame]) -> None:
    """Write sortables sheet."""
    if sortables is None or sortables.empty:
        return
    excel_utils.add_frame("SORTABLES", sortables, workbook, column_width=18)
write_custom_curves staticmethod
write_custom_curves(workbook, custom_curves)

Write custom curves sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_custom_curves(
    workbook: Workbook,
    custom_curves: Optional[Dict[str, Dict[str, pd.Series[Any]]]],
) -> None:
    """Write custom curves sheet."""
    if not custom_curves:
        return
    combined_df = DataSheetWriter._combine_custom_curves(custom_curves)
    if combined_df is not None and not combined_df.empty:
        excel_utils.add_frame(
            "CUSTOM_CURVES", combined_df, workbook, column_width=18
        )
write_gquery_results staticmethod
write_gquery_results(workbook, gquery_results)

Write gquery results sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_gquery_results(
    workbook: Workbook, gquery_results: Optional[pd.DataFrame]
) -> None:
    """Write gquery results sheet."""
    if gquery_results is None or gquery_results.empty:
        return
    excel_utils.add_frame("GQUERIES", gquery_results, workbook, column_width=18)
write_users staticmethod
write_users(workbook, users)

Write users sheet.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write_users(workbook: Workbook, users: Optional[pd.DataFrame]) -> None:
    """Write users sheet."""
    if users is None or users.empty:
        return
    excel_utils.add_frame("USERS", users, workbook, column_width=18)

HourlyCurvesWriter

Writes hourly curves to separate Excel file.

Functions
write staticmethod
write(curves_data, output_path, carriers)

Write hourly curves to Excel, organized by carrier.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write(
    curves_data: Dict[str, Dict[str, pd.DataFrame]],
    output_path: Path,
    carriers: Optional[Sequence[str]],
) -> None:
    """Write hourly curves to Excel, organized by carrier."""
    if not curves_data:
        logger.info("No hourly curves data available")
        return

    carrier_curves = HourlyCurvesWriter._organize_by_carrier(curves_data, carriers)
    HourlyCurvesWriter._write_carrier_sheets(carrier_curves, output_path)

AnnualExportsWriter

Writes annual exports to separate Excel file.

Functions
write staticmethod
write(exports_data, output_path)

Write annual exports to Excel file with validation.

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write(
    exports_data: Dict[str, Dict[str, pd.DataFrame]], output_path: Path
) -> None:
    """Write annual exports to Excel file with validation."""
    if not exports_data:
        logger.info("No export data available")
        return

    # Validate export type names
    from pyetm.models.packables.annual_exports_pack import AnnualExportsPack

    export_names = list(exports_data.keys())
    validated_names, warnings = AnnualExportsPack.validate_export_types(
        export_names
    )
    for warning in warnings:
        logger.warning("Annual exports: %s", warning)

    # Filter to only validated export types
    filtered_exports = {
        name: data for name, data in exports_data.items() if name in validated_names
    }

    if not filtered_exports:
        logger.warning(
            "Annual exports: No valid export types found, nothing to write"
        )
        return

    workbook = None
    try:
        workbook = Workbook(str(output_path), {"nan_inf_to_errors": True})

        for export_name in sorted(filtered_exports.keys()):
            AnnualExportsWriter._write_export_sheet(
                workbook, export_name, filtered_exports[export_name]
            )
    finally:
        if workbook is not None:
            workbook.close()

ExcelExporter

Handles Excel export for scenario data.

Functions
write staticmethod
write(export_data, path, scenarios)

Write export data collection to Excel format.

Parameters:

Name Type Description Default
export_data ExportDataCollection

The collected export data in generic format

required
path str

Output file path for the main Excel file

required
scenarios list[Any]

List of scenario objects for proper formatting

required

Returns:

Type Description
Path

Path to the created main Excel file

Source code in src/pyetm/exporters/excel_exporter.py
@staticmethod
def write(
    export_data: ExportDataCollection, path: str, scenarios: list[Any]
) -> Path:
    """
    Write export data collection to Excel format.

    Args:
        export_data: The collected export data in generic format
        path: Output file path for the main Excel file
        scenarios: List of scenario objects for proper formatting

    Returns:
        Path to the created main Excel file
    """
    PathManager.ensure_directory_exists(path)

    ExcelExporter._write_main_workbook(export_data, path, scenarios)
    ExcelExporter._write_separate_workbooks(export_data, Path(path))

    return Path(path)