Model/infrastructure/xlsx/scenario_export_workbook.py
Khalim Conn-Kowlessar 4bd90bf836 Render the scenario export workbook with a sheet per scenario 🟩
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 09:19:40 +00:00

36 lines
1.2 KiB
Python

"""Renders the Scenario Export workbook (ADR-0065).
One ``.xlsx`` with one sheet per Scenario (model A2), each sheet's rows shaped by
``domain.scenario_export`` and painted with the Monday-style branding in
``infrastructure.xlsx.branding``. Programmatic openpyxl (no template) so a
dynamic number of scenario sheets is handled natively.
"""
from __future__ import annotations
from io import BytesIO
from typing import Sequence
from openpyxl import Workbook
from domain.scenario_export.scenario_sheet import ExportSheet
def render_workbook(sheets: Sequence[tuple[str, ExportSheet]]) -> bytes:
"""Render the scenario sheets into a single branded ``.xlsx`` as bytes. Each
tuple is a Scenario name and its shaped sheet; sheet order follows the input
(the requested ``scenario_ids`` order)."""
workbook = Workbook()
default = workbook.active
if default is not None:
workbook.remove(default)
for name, sheet in sheets:
worksheet = workbook.create_sheet(title=name)
worksheet.append(list(sheet.columns))
for row in sheet.rows:
worksheet.append([row.get(column, "") for column in sheet.columns])
buffer = BytesIO()
workbook.save(buffer)
return buffer.getvalue()