Site icon Best Excel Tutorial

How to create Excel file in C#

The provided instructions and code are a basic guide to creating an Excel file in C# using the Microsoft Office Interop library.

Set Up Your Development Environment

Open Visual Studio and create a new Windows Forms Application project.

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.

Add Necessary References

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

C# code

Double-click on the button to open the code-behind file.
Replace any existing code with the following code:
using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelFileCreation
public partial class Form1 : Form
public Form1()
private void buttonCreateExcel_Click(object sender, EventArgs e)
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "Hello, Excel!";
MessageBox.Show("Excel file created. You can find the file at C:\\csharp-Excel.xlsx");
private void releaseObject(object obj)
{ System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
catch (Exception ex)
obj = null;
MessageBox.Show("Exception Occurred while releasing object: " + ex.ToString());

The code initializes Excel, creates a new workbook and worksheet, adds data to cell A1, saves the workbook, closes Excel, and then releases the Excel objects.

The releaseObject method is used to release COM objects and ensure proper resource management.

The Excel file is saved as “C:\csharp-Excel.xlsx” in this example. You can change the file path and name as needed.

Exit mobile version