Skip to content

Instantly share code, notes, and snippets.

@openize-cells-gists
Created May 22, 2024 12:51
Show Gist options
  • Save openize-cells-gists/feb1f5ecd00b17f06531a7832f0ed0aa to your computer and use it in GitHub Desktop.
Save openize-cells-gists/feb1f5ecd00b17f06531a7832f0ed0aa to your computer and use it in GitHub Desktop.
Adding Formulas to Cells in a Workbook in C#
// This example demonstrates how to add formulas to cells in a workbook.
using (Workbook wb = new Workbook())
{
// Accessing the first worksheet in the workbook.
Worksheet firstSheet = wb.Worksheets[0];
// Create a random number generator.
Random rand = new Random();
// Loop through the first 10 rows in column A.
for (int i = 1; i <= 10; i++)
{
// Construct a cell reference based on the current row.
string cellReference = $"A{i}";
// Access or create a cell at the specified cell reference.
Cell cell = firstSheet.Cells[cellReference];
// Generate a random number between 1 and 100.
double randomValue = rand.Next(1, 100);
// Assign the random number to the cell.
cell.PutValue(randomValue);
}
// After populating the first 10 cells with random numbers,
// we will use cell A11 to sum the values from A1 to A10.
Cell cellA11 = firstSheet.Cells["A11"];
cellA11.PutFormula("SUM(A1:A10)");
// Save the changes made to the workbook.
wb.Save(filePath);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment