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 150+ most used formulas. The whole list can be found on Calculation Engine help page.

The following example shows how you can use the GemBox.Spreadsheet calculation engine to calculate Excel cell formula values in Java.It shows how you can 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 cell's value (ExcelCell.getValue.

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

Excel formulas calculated with GemBox.Spreadsheet for Java
Screenshot of 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 the 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%");

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