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#.

svg viewer

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

  1. Open a new C# project on Visual Studio:
widget
  1. Right-click on the “References” option in the Solution Explorer and select “Add Reference”:
widget
  1. Select “Microsoft Excel 16.0 Object Library” from the COM list:
widget
  1. 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 files
using 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 worksheet
public void NewFile()
{
this.workbook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
this.worksheet = this.workbook.Worksheets[1];
}
// Method adds a new worksheet to the existing workbook
public void NewSheet()
{
Worksheet newSheet = excel.Worksheets.Add(After: this.worksheet);
}
// Method saves workbook at a specified path
public void SaveAs(string path)
{
workbook.SaveAs(path);
}
// Method closes Excel file
public void Close()
{
workbook.Close();
}
}
static void Main()
{
// Create an excel object
Excel file = new Excel();
// Create a new workbook with a single sheet
file.NewFile();
// Add a new sheet to the workbook
file.NewSheet();
// Saving the file in a speicifed path
file.SaveAs(@"file");
// Closing the file
file.Close();
}
}
  1. Visit the directory you selected to save your Excel file at and open file.xlsx to view a new Excel Workbook with two sheets:
widget
Copyright ©2024 Educative, Inc. All rights reserved