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
Select the project type ASP.NET Core Web App (Model-View-Controller).
Enter the name of your project.
Choose a suitable framework version and tick the Configure for HTTPS checkbox.
Your Solution Explorer looks like the image below.
Step 2: Install the required packages from the NuGet Package Manager
Select Microsoft.EntityFrameworkCore.SqlServer with a compatible version and install it.
Select Microsoft.EntityFrameworkCore.Tools with a compatible version and install it.
Select Microsoft.EntityFrameworkCore with a compatible version and install it.
Select ClosedXML with a compatible version and install it.
You can check the installed packages, as shown in the image below.
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.
Step 6: Register the DbContext in the Program.cs file, as shown in the image below.
Step 7: Run the Add-Migration "FirstMigration" command, as shown in the image below.
Step 8: Run the Update-Database command, as shown in the image below.
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.
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.
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;
}
}
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();
}
}
Step 10: Create a view and write the HTML code below in it, as shown in the image.
Now run the application. You will see the Export to Excel button, as shown in the image below.
Click the Export to Excel button shown above; it downloads an Excel sheet to your Downloads folder, as shown in the image below.
Open the downloaded Excel sheet; you can see the table data in it, as shown in the image below.