Add formula in Excel

  • VSTO
  • Spire.XLS
  • Download Sample Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using System.Drawing;

namespace VSTO
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Instantiate the Application object
            Excel.Application excelApp = Application;

            //Add a Workbook
            Excel.Workbook workbook = excelApp.Workbooks.Add();

            //Get the First worksheet
            Excel.Worksheet sheet = (Excel.Worksheet)workbook.Sheets["Sheet1"];

            //Access cells A1, A2, A3
            Excel.Range cell1 = sheet.Range["A1"];
            Excel.Range cell2 = sheet.Range["A2"];
            Excel.Range cell3 = sheet.Range["A3"];

            //Set value
            cell1.Value = 2;
            cell2.Value = 3;

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

            //Set the font color
            cell3.Font.Color = Color.Red;

            //Save the file
            workbook.SaveAs("FormulaExcel.xlsx");
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}

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["A2"];
            CellRange cell3 = sheet.Range["A3"];
            
            //Set value
            cell1.Value2 = 2;
            cell2.Value2 = 3;

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

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

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