添加单元格公式

向单元格添加公式

如何添加和计算公式?

可以通过使用单元格的Formula属性来添加、访问和修改单元格中的公式。Aspose.Cells.GridWeb支持从简单到复杂的用户定义公式。然而,Aspose.Cells.GridWeb还提供了大量的类似于Microsoft Excel的内置函数或公式。要查看完整的内置函数列表,请参考支持的函数列表。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Accessing the worksheet of the Grid that is currently active
GridWorksheet sheet = GridWeb1.WorkSheets[GridWeb1.ActiveSheetIndex];
// Putting some values to cells
sheet.Cells["A1"].PutValue("1st Value");
sheet.Cells["A2"].PutValue("2nd Value");
sheet.Cells["A3"].PutValue("Sum");
sheet.Cells["B1"].PutValue(125.56);
sheet.Cells["B2"].PutValue(23.93);
// Adding a simple formula to "B3" cell
sheet.Cells["B3"].Formula = "=SUM(B1:B2)";

将公式添加到 B3 单元格,但未由 GridWeb 计算

todo:image_alt_text

在上面的屏幕截图中,您可以看到已经在B3单元格中添加了一个公式,但尚未计算。要计算所有公式,请在向工作表添加公式后,调用GridWeb控件的GridWorksheetCollection的CalculateFormula方法。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Calculating all formulas added in worksheets
GridWeb1.WorkSheets.CalculateFormula();

引用其他工作表中的单元格

使用 Aspose.Cells.GridWeb,可以在其公式中引用存储在不同工作表中的值,从而创建复杂的公式。

从不同工作表引用单元格值的语法是 SheetName!CellName。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// Adding a bit complex formula to "A1" cell
sheet1.Cells["B6"].Formula = "=(SUM(A1:A5)/AVERAGE(B1:B5))-Sheet2!B1";