Create, Manipulate or Remove Scenarios from Worksheets
Contents
[
Hide
]
Sometimes, you need to create, manipulate or delete scenarios in spreadsheets. A scenario is a named what-if model that includes variable input cells linked together by one or more formulas. Before creating a scenario, design a worksheet so that it contains at least one formula that depends on cells into which different values can be inserted. The following example shows how to create and remove scenarios from a worksheet using the Aspose.Cells APIs.
Aspose.Cells provides some useful classes, for example ScenarioCollection, Scenario, ScenarioInputCellCollection and ScenarioInputCell. It also provides the Worksheet.Scenarios property. The sample code below opens an XLSX Excel file (that contains some scenarios) and removes an existing scenario from the worksheet. It also adds a new scenario before saving the Excel file. It uses a very simple template file that contains a scenario.
After executing the code, an existing scenario is removed and a new scenario is added to the worksheet.
The output file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java | |
// The path to the documents directory. | |
String dataDir = Utils.getDataDir(CreateScenariosfromWorksheets.class); | |
// Instantiate the Workbook | |
// Load an Excel file | |
Workbook workbook = new Workbook(dataDir + "Bk_scenarios.xlsx"); | |
// Access first worksheet | |
Worksheet worksheet = workbook.getWorksheets().get(0); | |
// Remove the existing first scenario from the sheet | |
worksheet.getScenarios().removeAt(0); | |
// Create a scenario | |
int i = worksheet.getScenarios().add("MyScenario"); | |
// Get the scenario | |
Scenario scenario = worksheet.getScenarios().get(i); | |
// Add comment to it | |
scenario.setComment("Test sceanrio is created."); | |
// Get the input cells for the scenario | |
ScenarioInputCellCollection sic = scenario.getInputCells(); | |
// Add the scenario on B4 (as changing cell) with default value | |
sic.add(3, 1, "1100000"); | |
// Save the Excel file. | |
workbook.save(dataDir + "outBk_scenarios1.xlsx"); |