Calcular Fórmulas

Agregar fórmulas y calcular resultados

Aspose.Cells tiene un motor de cálculo de fórmulas incorporado. No solo puede volver a calcular fórmulas importadas desde plantillas de diseño, sino que también admite calcular los resultados de fórmulas agregadas en tiempo de ejecución.

Aspose.Cells admite la mayoría de las funciones o fórmulas que son parte de Microsoft Excel (Lee una lista de las funciones admitidas por el motor de cálculo). Estas funciones se pueden utilizar a través de las APIs o las hojas de cálculo del diseñador. Aspose.Cells soporta un amplio conjunto de fórmulas matemáticas, de cadena, booleanas, de fecha/hora, estadísticas, de base de datos, de búsqueda y referencia.

Utilice la propiedad Formula o los métodos SetFormula(…) de la clase Cell para agregar una fórmula a una celda. Al aplicar una fórmula, siempre comience la cadena con un signo igual (=) como lo hace al crear una fórmula en Microsoft Excel y use una coma (,) para delimitar los parámetros de función.

Para calcular los resultados de las fórmulas, el usuario puede llamar al método CalculateFormula de la clase Workbook que procesa todas las fórmulas incrustadas en un archivo de Excel. O, el usuario puede llamar al método CalculateFormula de la clase Worsheet que procesa todas las fórmulas incrustadas en una hoja. O, el usuario también puede llamar al método Calculate de la clase Cell que procesa la fórmula de una celda:

// 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.getSharedDataDir(CalculatingFormulas.class) + "formulas/";
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Adding a new worksheet to the Excel object
int sheetIndex = workbook.getWorksheets().add();
// Obtaining the reference of the newly added worksheet by passing its sheet index
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex);
// Adding a value to "A1" cell
worksheet.getCells().get("A1").putValue(1);
// Adding a value to "A2" cell
worksheet.getCells().get("A2").putValue(2);
// Adding a value to "A3" cell
worksheet.getCells().get("A3").putValue(3);
// Adding a SUM formula to "A4" cell
worksheet.getCells().get("A4").setFormula("=SUM(A1:A3)");
// Calculating the results of formulas
workbook.calculateFormula();
// Get the calculated value of the cell
String value = worksheet.getCells().get("A4").getStringValue();
// Saving the Excel file
workbook.save(dataDir + "CalculatingFormulas_out.xls");

Importante saber

Cálculo directo de fórmulas

Aspose.Cells tiene un motor de cálculo de fórmulas incorporado. Además de calcular las fórmulas importadas de un archivo de diseñador, Aspose.Cells puede calcular directamente los resultados de las fórmulas.

A veces, es necesario calcular directamente los resultados de las fórmulas sin agregarlas a una hoja de cálculo. Los valores de las celdas utilizados en la fórmula ya existen en una hoja de cálculo y todo lo que necesita es encontrar el resultado de esos valores en función de alguna fórmula de Microsoft Excel sin agregar la fórmula en una hoja de cálculo.

Puede utilizar las APIs del motor de cálculo de fórmulas de Aspose.Cells para Worksheet hasta calculate los resultados de dichas fórmulas sin agregarlas a la hoja de cálculo:

// 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.getSharedDataDir(DirectCalculationFormula.class) + "formulas/";
// Create a workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Put 20 in cell A1
Cell cellA1 = worksheet.getCells().get("A1");
cellA1.putValue(20);
// Put 30 in cell A2
Cell cellA2 = worksheet.getCells().get("A2");
cellA2.putValue(30);
// Calculate the Sum of A1 and A2
Object results = worksheet.calculateFormula("=Sum(A1:A2)");
// Print the output
System.out.println("Value of A1: " + cellA1.getStringValue());
System.out.println("Value of A2: " + cellA2.getStringValue());
System.out.println("Result of Sum(A1:A2): " + results.toString());

El código anterior produce la siguiente salida:

Value of A1: 20
Value of A2: 30
Result of Sum(A1:A2): 50.0

Calculando fórmulas repetidamente

Cuando hay muchas fórmulas en el libro de trabajo y el usuario necesita calcularlas repetidamente con modificando solo una pequeña parte de ellas, puede ser útil para el rendimiento habilitar la cadena de cálculo de fórmulas: FormulaSettings.EnableCalculationChain.

// 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.getSharedDataDir(CalculatingFormulasOnce.class) + "formulas/";
// Load the template workbook
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Print the time before formula calculation
System.out.println(DateTime.getNow());
// Set the CreateCalcChain as true
workbook.getSettings().getFormulaSettings().setEnableCalculationChain(true);
// Calculate the workbook formulas
workbook.calculateFormula();
Cells cells = workbook.getWorksheets().get("Sheet1").getCells();
//with original values, the calculated result
System.out.println(cells.get("A11").getValue());
//update one value the formula depends on
cells.get("A5").putValue(15);
// Calculate the workbook formulas again, in fact only A11 needs to be and will be calculated
workbook.calculateFormula();
//check the re-calculated value
System.out.println(cells.get("A11").getValue());
// Print the time after formula calculation
System.out.println(DateTime.getNow());

Importante saber

Temas avanzados