How To Create Excel File In C#?

Follow these steps to create Excel file in C#.

Launch Visual Studio

Note: You can use older version of visual studio

Create a new project and add a Button to the form

Note: To create a new project go to File (on the top left corner), Select new and select project.

visual studio

Click on Project tab and select Add Reference. Select Microsoft Excel 12.0 Object Library and click ok.

click ok

Double click on the button. First delete the code that is written there. Copy and paste the following

source code using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel; namespace WindowsApplication1
 { 
public partial class Form1 : Form 
{ 
public Form1() 
{ 
InitializeComponent();
 } 
private void button1_Click(object sender, EventArgs e) 
{ 
Excel.Application xlApp ; 
Excel.Workbook xlWorkBook ; 
Excel.Worksheet xlWorkSheet ; 
object misValue = System.Reflection.Missing.Value; 
xlApp = new Excel.ApplicationClass(); 
xlWorkBook = xlApp.Workbooks.Add(misValue); 
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com"; 
xlWorkBook.SaveAs("csharp-Excel.xls", 
Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, 
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); 
xlWorkBook.Close(true, misValue, misValue); 
xlApp.Quit(); releaseObject(xlWorkSheet);
releaseObject(xlWorkBook); 
releaseObject(xlApp); 
MessageBox.Show("Excel file created , you can find the file c:\csharp-Excel.xls"); 
} 
private void releaseObject(object obj) 
{
try 
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; 
}
catch (Exception ex) 
{ 
obj = null; 
MessageBox.Show("Exception Occured while releasing object " + ex.ToString()); 
}
finally 
{
GC.Collect(); 
} 
} 
} 
}

This is how to use C# programming language to create simple Excel spreadsheet.

Template

You can download the Template here – Download
Previous articleAvoid Errors Using IFERROR-Everyone Should Know
Next articleLinking Text Box To A Specific Cell