Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,6 @@ examples/output

# Files from editable installs of pip
/InOutModule.egg-info/

# Operating system files
.DS_Store
31 changes: 31 additions & 0 deletions ExcelWriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import numpy as np
import openpyxl
import pandas as pd
import pyomo.core
from openpyxl.utils.dataframe import dataframe_to_rows

import ExcelReader
Expand Down Expand Up @@ -303,6 +304,36 @@ def write_dData_Packages(self, dData_Packages: pd.DataFrame, folder_path: str) -
self._write_Excel_from_definition(dData_Packages, folder_path, "Data_Packages")


def model_to_excel(model: pyomo.core.Model, target_path: str) -> None:
"""
Write all variables of the given Pyomo model to an Excel file.

:param model: The Pyomo model to be written to Excel.
:param target_path: Path to the target Excel file.
:return: None
"""
printer.information(f"Writing model to '{target_path}'")
wb = openpyxl.Workbook()
ws = wb.active

for i, var in enumerate(model.component_objects(pyomo.core.Var, active=True)):
if i == 0: # Use the automatically existing sheet for the first variable
ws.title = str(var)
else: # Create a sheet for each (other) variable
ws = wb.create_sheet(title=str(var))

# Prepare the data from the model and prepare the header
data = [(j, v.value if not v.stale else None) for j, v in var.items()]
col_number = len(data[0][0]) if not isinstance(data[0][0], str) else 1
ws.append([f"index_{j}" for j in range(col_number)] + [str(var)])

# Write data to the sheet
for j, v in data:
ws.append(([j_index for j_index in j] if not isinstance(j, str) else [j]) + [v])

wb.save(target_path)


if __name__ == "__main__":
import argparse
from rich_argparse import RichHelpFormatter
Expand Down
Loading