Excel Formula Calculation in Java

With GemBox.Spreadsheet for Java, you can calculate a large range of different formulas - from a simplest formula that calculates the sum of two fields, up to a complex formula that includes brackets, a range of cells, cells that contain other formulas, and even an iterative calculation. GemBox.Spreadsheet currently supports 140+ most used formulas. The whole list can be found here.

The following example shows how to use the GemBox.Spreadsheet calculation engine to calculate Excel cell formula values in Java.It demonstrates how to set cell formulas and calculate their values by calling one of the methods: ExcelCell.calculate, ExcelWorksheet.calculate, or ExcelFile.calculate. The calculation result is stored in ExcelCell's value.

Notice that below you have Run options where you can choose output file format.

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

class Program {

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

        ExcelFile workbook = new ExcelFile();
        ExcelWorksheet worksheet = workbook.addWorksheet("Formula Calculation");

        // Some formatting.
        ExcelRow row = worksheet.getRow(0);

        ExcelColumn column = worksheet.getColumn(0);
        column.setWidth(250, LengthUnit.PIXEL);
        column = worksheet.getColumn(1);
        column.setWidth(250, LengthUnit.PIXEL);

        // Use first row for column headers.
        worksheet.getCell("B1").setValue("Calculated value");

        // Enter some Excel formulas as text in first column.
        worksheet.getCell("A2").setValue("=1 + 1");
        worksheet.getCell("A3").setValue("=3 * (2 - 8)");
        worksheet.getCell("A4").setValue("=3 + ABS(B3)");
        worksheet.getCell("A5").setValue("=B4 > 15");
        worksheet.getCell("A6").setValue("=IF(B5, \"Hello world\", \"World hello\")");
        worksheet.getCell("A7").setValue("=B6 & \" example\"");
        worksheet.getCell("A9").setValue("=POWER(B8, 3) * 0.45%");

        // Set text from first column as second row cell's formula.
        int rowIndex = 1;
        while (worksheet.getCell(rowIndex, 0).getValueType() != CellValueType.NULL)
            worksheet.getCell(rowIndex, 1).setFormula(worksheet.getCell(rowIndex++, 0).getStringValue());

        // GemBox.Spreadsheet supports single Excel cell calculation, ...

        // ... Excel worksheet calculation,

        // ... and whole Excel file calculation.


        workbook.save("Formula Calculation.%OutputFileType%");

Check next example or download examples from GitHub.