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
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 ExcelDataReader 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 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.
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 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();
}
}
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 Upload Excel button, as shown in the image below.
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.
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.
Below is the Excel sheet that we uploaded. You can compare it with the database entries; they are exactly the same.