Iterative Calculation

The following example shows how you can use the GemBox.Spreadsheet calculation engine to calculate cell formulas with circular references.

The example shows how you can enable and use an iterative calculation in GemBox.Spreadsheet. By default, circular references are not allowed, so we first enable them by setting CalculationOptions.setEnableIterativeCalculation.

Column A contains a simple iterative calculation example where the calculation is limited by CalculationOptions.getMaximumIterations. On calling the calculate method, the formula will be calculated CalculationOptions.getMaximumIterations times before the calculation is terminated and the last calculation result is set as the cell value.

Although the calculation of all circular references is limited by CalculationOptions.getMaximumIterations, some iterative calculations may be terminated before the limit is reached if the difference between the previous and current calculation is less than CalculationOptions.getMaximumChange value. The formulas in column B demonstrate such an iterative calculation process.

Excel formula with circular reference calculated with GemBox.Spreadsheet for Java
Screenshot of Excel formula with circular reference calculated with GemBox.Spreadsheet for Java
import com.gembox.spreadsheet.*;

class Program {

    public static void main(String[] args) throws {
        // If using the Professional version, put your serial key below.

        ExcelFile workbook = new ExcelFile();

        // Set calculation options.

        // Add new worksheet
        ExcelWorksheet worksheet = workbook.addWorksheet("Iterative Calculation");

        // Some column formatting.
        worksheet.getColumn(0).setWidth(50, LengthUnit.PIXEL);
        worksheet.getColumn(1).setWidth(100, LengthUnit.PIXEL);

        // Simple example of circular reference limited by MaximumIterations in column A.
        worksheet.getCell("A2").setFormula("=A1 + 1");

        // Simple example of circular reference limited by MaximumChange in column B.
        worksheet.getCell("B2").setFormula("=B3 * 0.03");
        worksheet.getCell("B3").setFormula("=B1 + B2");

        // Calculate all cells.
        worksheet.calculate();"Iterative Calculation.%OutputFileType%");

See also

Next steps

GemBox.Spreadsheet for Java is a component that enables you to read, write, edit and convert spreadsheet files from your applications using one simple API.

Download Buy