Add formula in Excel

  • NPOI
  • Spire.XLS
  • Download Sample Code

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOI
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create workbook
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("MySheet");

            //Create cells
            IRow row = sheet.CreateRow(0);
            ICell cell1 = row.CreateCell(0);
            ICell cell2 = row.CreateCell(1);
            ICell cell3 = row.CreateCell(2);
            ICell sumCell = row.CreateCell(3);

            //Set the value of the cells
            cell1.SetCellValue(10);
            cell2.SetCellValue(15);
            cell3.SetCellValue(20);

            //Add formula
            sumCell.SetCellFormula("sum(A1:C1)");
            
            //Save the file
            FileStream file = File.Create("ExcelFormula.xlsx");
            workbook.Write(file);
            file.Close();

            //Launch the file
            System.Diagnostics.Process.Start("ExcelFormula.xlsx");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Xls;
using System.Drawing;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize a new instance of workbook
            Workbook workbook = new Workbook();

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Access cells A1, A2, A3
            CellRange cell1 = sheet.Range["A1"];
            CellRange cell2 = sheet.Range["B1"];
            CellRange cell3 = sheet.Range["C1"];
            CellRange cellNum = sheet.Range["D1"];

            //Set value
            cell1.Value2 = 10;
            cell2.Value2 = 15;
            cell3.Value2 = 20;

            //Add formula in cell3
            cellNum.Formula = "=Sum(A1:A3)";

            //Set the font color
            cellNum.Style.Font.Color = Color.Red;

            //Save and Launch
            workbook.SaveToFile("FormulaExcel.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("FormulaExcel.xlsx");
        }
    }
}