How to create an Excel file with C#
Knowing how to automate the creation of Microsoft Excel workbooks and worksheets can save individuals and organizations a lot of valuable time. In this shot, we will cover how we can do so using C#.
Before moving ahead, ensure you have a development environment with the .NET Framework set up on your device. For this shot, we will use Microsoft’s Visual Studio.
Let's get started
- Open a new C# project on Visual Studio:
- Right-click on the “References” option in the Solution Explorer and select “Add Reference”:
- Select “Microsoft Excel 16.0 Object Library” from the COM list:
- Now, we can write the actual code in Visual Studio to create a new Excel Workbook and a new Worksheet in that Workbook:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;// Add the following namespace to work with excel filesusing Microsoft.Office.Interop.Excel;using _excel = Microsoft.Office.Interop.Excel;namespace Excel_with_C_Sharp{class Excel{// Create an excel application object, workbook oject and worksheet object_Application excel = new _excel.Application();Workbook workbook;Worksheet worksheet;// Method creates a new Excel file by creating a new Excel workbook with a single worksheetpublic void NewFile(){this.workbook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);this.worksheet = this.workbook.Worksheets[1];}// Method adds a new worksheet to the existing workbookpublic void NewSheet(){Worksheet newSheet = excel.Worksheets.Add(After: this.worksheet);}// Method saves workbook at a specified pathpublic void SaveAs(string path){workbook.SaveAs(path);}// Method closes Excel filepublic void Close(){workbook.Close();}}static void Main(){// Create an excel objectExcel file = new Excel();// Create a new workbook with a single sheetfile.NewFile();// Add a new sheet to the workbookfile.NewSheet();// Saving the file in a speicifed pathfile.SaveAs(@"file");// Closing the filefile.Close();}}
- Visit the directory you selected to save your Excel file at and open
file.xlsxto view a new Excel Workbook with two sheets:
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved