Skip to content

How to Import Data From Excel to Database in ASP.NET Core

Problem definition: We need to import Excel data, as it is, into a SQL Server database in an ASP.NET Core application. For example, we have an Excel sheet with hundreds of rows and a few columns that we need to save into a database table such as tblStudents, by uploading the sheet with an Upload button.

Below is the step-by-step process, explained in detail, so that you can import data from an Excel sheet into the database 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 ExcelDataReader with a compatible version and install it.

Installing the ExcelDataReader NuGet package

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

Solution Explorer with ExcelDataReader and EF Core packages and the uploaded Excel file in wwwroot/uploads

Step 3: Create a Student model class for importing data from Excel into the database.

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 controller named TestController with an action method named UploadExcelIntoDB, and write the code in it, as shown in the image and code below.

public class TestController : Controller
   {
       private readonly AppDbContext db;
       public TestController(AppDbContext _db)
       {
           db = _db;
       }
     public IActionResult  UploadExcelIntoDB()
       {
           return View();
       }
       [HttpPost]
       public async Task<IActionResult> UploadExcelIntoDB(IFormFile file)
       {
           Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
           if(file != null && file.Length>0)
           {
               var folderUpload=$"{Directory.GetCurrentDirectory()}\\wwwroot\\uploads";
               if(!Directory.Exists(folderUpload))
               {
                   Directory.CreateDirectory(folderUpload);
               }
               var path_of_file=Path.Combine(folderUpload, file.FileName);
               using (var stream = new FileStream(path_of_file, FileMode.Create))
               {
                   await file.CopyToAsync(stream);
               }
               using(var stream=System.IO.File.Open(path_of_file,FileMode.Open,FileAccess.Read))
               {
                   using(var reader  = ExcelReaderFactory.CreateReader(stream))
                   {
                       do
                       {
                           bool isHeaderRemoved = false;
                           while(reader.Read())
                           {
                               if(!isHeaderRemoved)
                               {
                                   isHeaderRemoved = true;
                                   continue;
                               }
                               Student st = new Student();
                               st.StudentName = reader.GetValue(1).ToString();
                               st.Branch = reader.GetValue(2).ToString();
                               st.Fees=Convert.ToInt32( reader.GetValue(3).ToString());
                               st.Address = reader.GetValue(4).ToString();
                               st.DateOfBirth =Convert.ToDateTime( reader.GetValue(5).ToString());
                                db.tblStudents.Add(st);
                               await db.SaveChangesAsync();
                           }
                       }     while (reader.NextResult());
                   }                  
               }
           }
           return View();
       }      
   }
UploadExcelIntoDB action saving the uploaded Excel file to wwwroot/uploads
Reading Excel rows with ExcelDataReader, skipping the header and saving students to the database

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

Razor view with the Excel file upload form

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

Running app with the Upload Excel button

Click the Upload Excel button shown above. It uploads the Excel sheet to the uploads folder inside wwwroot, as shown in the image below, and then saves the data in the database, as shown in the database image.

Solution Explorer with ExcelDataReader and EF Core packages and the uploaded Excel file in wwwroot/uploads

After clicking Upload, you can see the uploaded file in the wwwroot/uploads folder, as shown above, and the data is saved in the tblStudents table, as you can see in the image below.

Imported student records in the tblStudents table

Below is the Excel sheet that we uploaded. You can compare it with the database entries; they are exactly the same.

Excel sheet with the student data to import