Create Excel File with Formulas in C#

Step 1: Create new windows form application.

Step 2: In solution explorer right click on References and select Add References. Then Add Reference form will open as follows. In that select .Net tab and add "Microsoft.Office.Interop.Excel"  reference.

Step 3: Create windows from like below.
 

Step 4: Write the following code.

  1. using System;  
  2. using System.Windows.Forms;  
  3. using Excel = Microsoft.Office.Interop.Excel;  
  4. namespace ExecelWithFormula   
  5. {  
  6.     public partial class Form1: Form  
  7.     {  
  8.         public Form1()   
  9.         {  
  10.             InitializeComponent();  
  11.         }  
  12.         private void button1_Click(object sender, EventArgs e)   
  13.         {  
  14.             Excel.Application excelApp = new Excel.Application();  
  15.             Excel.Workbook workbook = null;  
  16.             Excel.Workbooks workbooks = null;  
  17.             Excel._Worksheet worksheet = null;  
  18.             workbooks = excelApp.Workbooks;  
  19.             workbook = workbooks.Add(1);  
  20.             worksheet = (Excel.Worksheet) workbook.Sheets[1];  
  21.             excelApp.Visible = true;  
  22.             worksheet.Cells[1, 1] = "Value1";  
  23.             worksheet.Cells[1, 2] = "Value2";  
  24.             worksheet.Cells[1, 3] = "Addition";  
  25.             worksheet.Cells[2, 1] = textBox1.Text;  
  26.             worksheet.Cells[2, 2] = textBox2.Text;  
  27.             worksheet.Cells[2, 3].Formula = "=SUM(A2,B2)";  
  28.         }  
  29.     }  
  30. }  
Step 5: Run the application.

Step 6: Enter values of value1 and value2 and click on Create Excel

 

Step 7: Excel will be generated with SUM formula in it.

 

Step 8 : Then change value1 and value2 and check result.

Ebook Download
View all
Learn
View all