Skip to content

How to Export Data into Excel in ASP.NET Core

Problem definition: We need to export table data to an Excel sheet, with the column names as the header row, in an ASP.NET Core application. For example, we have a tblStudents master table, and we need to export the student data to an Excel sheet when the user clicks an Export button.

Below is the step-by-step process, explained in detail, so that you can export data to an Excel sheet in your application.

Step 1: Create a project in Microsoft Visual Studio

Visual Studio start window with Create a new project selected

Select the project type ASP.NET Core Web App (Model-View-Controller).

Selecting the ASP.NET Core Web App (Model-View-Controller) template in Visual Studio

Enter the name of your project.

Entering the project name in the Configure your new project dialog

Choose a suitable framework version and tick the Configure for HTTPS checkbox.

Choosing the .NET framework version and Configure for HTTPS option

Your Solution Explorer looks like the image below.

Solution Explorer of the new ASP.NET Core MVC project

Step 2: Install the required packages from the NuGet Package Manager

Opening NuGet Package Manager to install the required packages

Select Microsoft.EntityFrameworkCore.SqlServer with a compatible version and install it.

Installing the Microsoft.EntityFrameworkCore.SqlServer NuGet package

Select Microsoft.EntityFrameworkCore.Tools with a compatible version and install it.

Installing the Microsoft.EntityFrameworkCore.Tools NuGet package

Select Microsoft.EntityFrameworkCore with a compatible version and install it.

Installing the Microsoft.EntityFrameworkCore NuGet package

Select ClosedXML with a compatible version and install it.

Installing the ClosedXML NuGet package

You can check the installed packages, as shown in the image below.

Installed ClosedXML and Entity Framework Core packages in Solution Explorer

Step 3: Create a Student model class for exporting data from the database to Excel.

public class Student
   {
       [Key]
       public int StudentId { get; set; }
       public string StudentName { get; set; }
       public string Branch { get; set; }
       public int Fees { get; set; }
       public string Address { get; set; }
       public DateTime DateOfBirth { get; set; }
   }  

Step 4: Create an AppDbContext class and add the Student model class as a DbSet, as shown in the image and code below.

public class AppDbContext : DbContext
   {
       public AppDbContext(DbContextOptions options)
       : base(options)
       {

       }
       public DbSet<Student> tblStudents { get; set; }
   }  

Step 5: Define the connection string in the appsettings.json file, as shown in the image below.

SQL Server connection string defined in appsettings.json

Step 6: Register the DbContext in the Program.cs file, as shown in the image below.

Registering AppDbContext with the SQL Server connection string in Program.cs

Step 7: Run the Add-Migration "FirstMigration" command, as shown in the image below.

Running Add-Migration FirstMigration in Package Manager Console

Step 8: Run the Update-Database command, as shown in the image below.

Running Update-Database in Package Manager Console

After running the migration commands above, you can see a new Migrations folder in the solution, with an auto-generated FirstMigration class, as shown in the image below.

Migrations folder with the auto-generated FirstMigration class

After running the migration commands above, you can see the new tables in the database, along with the auto-generated migration history table. Insert data into tblStudents, as shown in the image below.

tblStudents table with student data in SQL Server

Step 9: Create a class named FileProcessing with a public method named CreateExcelFile that takes a list of students as a parameter and returns a MemoryStream, as shown in the code and image below.

public class FileProcessing
 {
     public MemoryStream CreateExcelFile(List<Student> students)
     {
         var Excelworkbook = new XLWorkbook();
         IXLWorksheet worksheet = Excelworkbook.Worksheets.Add("Students");
         //Create Header of Excel sheet
         worksheet.Cell(1, 1).Value = "Student Id"; 
         worksheet.Cell(1, 2).Value = "Student Name"; 
         worksheet.Cell(1, 3).Value = "Branch"; 
         worksheet.Cell(1, 4).Value = "Fees"; 
         worksheet.Cell(1, 5).Value = "Address"; 
         worksheet.Cell(1, 6).Value = "Date Of Birth"; 
         int row = 2;
         foreach (var st in students)
         {
             worksheet.Cell(row, 1).Value = st.StudentId;
             worksheet.Cell(row, 2).Value = st.StudentName;
             worksheet.Cell(row, 3).Value = st.Branch;
             worksheet.Cell(row, 4).Value = st.Fees;
             worksheet.Cell(row, 5).Value = st.Address;
             worksheet.Cell(row, 6).Value = st.DateOfBirth;
             row++; 
         }
        var Memorystream = new MemoryStream();
         Excelworkbook.SaveAs(Memorystream);
         Memorystream.Position = 0;
        return Memorystream;
     }
 } 
Class that writes student data to an Excel worksheet with ClosedXML

Step 9: Create a controller named TestController with two action methods, ExportToExcel and DownloadExcel, and write the code in them, as shown in the image and code below.

public class TestController : Controller
  {
      private readonly AppDbContext db;
      public TestController(AppDbContext _db)
      {
          db = _db;
      }

     [HttpPost]
      public IActionResult ExportToExcel()
      {
       var students = db.tblStudents.ToList();
       FileProcessing excelFileProcessing = new FileProcessing();
      var stream = excelFileProcessing.CreateExcelFile(students);
      string excelSheetName = $"Students-{System.DateTime.Now}.xlsx";
      return File(stream, "application/vnd.openxmlformats-officedocument.
      spreadsheetml.sheet", excelSheetName);
      }
      [HttpGet]
      public IActionResult DownloadExcel()
      {
          return View();
      }
  } 
Controller action returning the Excel file for download

Step 10: Create a view and write the HTML code below in it, as shown in the image.

Razor view with the Export to Excel button

Now run the application. You will see the Export to Excel button, as shown in the image below.

Running app with the Export to Excel button

Click the Export to Excel button shown above; it downloads an Excel sheet to your Downloads folder, as shown in the image below.

Downloaded Students Excel file in the Downloads folder

Open the downloaded Excel sheet; you can see the table data in it, as shown in the image below.

Exported student data opened in Excel