diff --git a/.gitignore b/.gitignore index b2d0943..b39262e 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,6 @@ examples/output # Files from editable installs of pip /InOutModule.egg-info/ + +# Operating system files +.DS_Store diff --git a/ExcelWriter.py b/ExcelWriter.py index 95cdc03..50d95c5 100644 --- a/ExcelWriter.py +++ b/ExcelWriter.py @@ -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 @@ -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