Introduction

Today we will learn how to import the Excel or CSV file to the SQL Server table through an ASP.Net MVC application. To insert or update the record we will use the stored procedure. Refere to my previous article SQL Bulk Insert And Update Records Using Stored Procedures to learn how to create the stored procedure for same. We will use the same stored procedure created in my previous article to import the file.
Prerequisite
Basic knowledge of Asp.Net MVC controller, View and Entity Framework.
Step 1
First, we will create Controller action to read the XLS file and convert the data to list. To read the Excel file we will use a packge named Excel Data Reader.
Go to nuget package manager and install these two package,
  1. ExcelDataReader
  2. ExcelDataReader.DataSet.
Step 2
Create a model named Employee and paste the below code .
  1. public class Employee
  2. {
  3. public int Id { get; set; }
  4. public string EmpName { get; set; }
  5. public string Position { get; set; }
  6. public string Location { get; set; }
  7. public int Age { get; set; }
  8. public int Salary { get; set; }
  9. }
Step 3
Create a controller named EmployeeController and Create action method named ImportFile() as below.
  1. public class EmployeeController : Controller
  2. {
  3. private readonly EmployeeDbContext _dbContext;
  4. public EmployeeController()
  5. {
  6. _dbContext = new EmployeeDbContext();
  7. }
  8. // GET: Student
  9. public ActionResult Index()
  10. {
  11. return View();
  12. }
  13. [HttpPost]
  14. public async Task<ActionResult> ImportFile()
  15. {
  16. return View("Index");
  17. }
  18. }
Here we have created two actions named Index and ImportFile. And also I have created the instance of DbContext (Entity Framework Context) class.
Step 4
Now we will create a method to read data from an Excel file and it will return the data in list format. Below is the sample image of CSV file that we are going to import.
Import Excel File To SQL Table In ASP.NET MVC
Note
We will use the first row of file as header or column name to map data to list. Value of first row should be same as mentioned in image because we are going to map the data based on that value only.
Now create a method in Employee Controller to read the CSV file and and return data into list format, paste the below code in Employee Controller.
  1. private List<Employee> GetDataFromCSVFile(Stream stream)
  2. {
  3. var empList = new List<Employee>();
  4. try
  5. {
  6. using (var reader = ExcelReaderFactory.CreateCsvReader(stream))
  7. {
  8. var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
  9. {
  10. ConfigureDataTable = _ => new ExcelDataTableConfiguration
  11. {
  12. UseHeaderRow = true // To set First Row As Column Names
  13. }
  14. });
  15. if (dataSet.Tables.Count > 0)
  16. {
  17. var dataTable = dataSet.Tables[0];
  18. foreach (DataRow objDataRow in dataTable.Rows)
  19. {
  20. if (objDataRow.ItemArray.All(x => string.IsNullOrEmpty(x?.ToString()))) continue;
  21. empList.Add(new Employee()
  22. {
  23. Id = Convert.ToInt32(objDataRow["ID"].ToString()),
  24. EmpName = objDataRow["Name"].ToString(),
  25. Position = objDataRow["Position"].ToString(),
  26. Location = objDataRow["Location"].ToString(),
  27. Age = Convert.ToInt32(objDataRow["Age"].ToString()),
  28. Salary = Convert.ToInt32(objDataRow["Salary"].ToString()),
  29. });
  30. }
  31. }
  32. }
  33. }
  34. catch (Exception)
  35. {
  36. throw;
  37. }
  38. return empList;
  39. }
The above method is using the nuget pacakge ExcelDataReader and reading the value from CSV file. ExcelDataReader will return the data in DataTable object. We have converted that DataTable object into List.
Step 5
We have created the method to read CSV file and get data in List format. Now we will create a file upload control to upload the file from webpage. Create a view for EmployeeController named as Index and paste the below code to create a file upload controller on webpage.
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Index</h2>
  5. <div class="row">
  6. <div class="col-sm-12" style="padding-bottom:20px">
  7. <div class="col-sm-2">
  8. <span>Select File :</span>
  9. </div>
  10. <div class="col-sm-3">
  11. <input class="form-control" type="file" name="importFile" id="importFile" />
  12. </div>
  13. <div class="col-sm-3">
  14. <input class="btn btn-primary" id="btnUpload" type="button" value="Upload" />
  15. </div>
  16. </div>
  17. </div>
Now we will call the ImportFile action of EmployeeController through ajax call from the webpage. And we will send the file as formdata through ajax call. Add the below code in your Index view.
  1. @section scripts{
  2. <script>
  3. $(document).on("click", "#btnUpload", function () {
  4. var files = $("#importFile").get(0).files;
  5. var formData = new FormData();
  6. formData.append('importFile', files[0]);
  7. $.ajax({
  8. url: '/Employee/ImportFile',
  9. data: formData,
  10. type: 'POST',
  11. contentType: false,
  12. processData: false,
  13. success: function (data) {
  14. if (data.Status === 1) {
  15. alert(data.Message);
  16. } else {
  17. alert("Failed to Import");
  18. }
  19. }
  20. });
  21. });
  22. </script>
  23. }
On click of Upload button this code will get executed. It will read the file from file input control and will make he Ajax call file be sent as formdata to controller.
Step 6
Now we have to update our controller action to read the file and send from webpage and import it into database. Update the ImportFile action of Employee Controller as below.
  1. [HttpPost]
  2. public async Task<ActionResult> ImportFile(HttpPostedFileBase importFile)
  3. {
  4. if (importFile == null) return Json(new { Status = 0, Message = "No File Selected" });
  5. try
  6. {
  7. var fileData = GetDataFromCSVFile(importFile.InputStream);
  8. var dtEmployee = fileData.ToDataTable();
  9. var tblEmployeeParameter = new SqlParameter("tblEmployeeTableType", SqlDbType.Structured)
  10. {
  11. TypeName = "dbo.tblTypeEmployee",
  12. Value = dtEmployee
  13. };
  14. await _dbContext.Database.ExecuteSqlCommandAsync("EXEC spBulkImportEmployee @tblEmployeeTableType", tblEmployeeParameter);
  15. return Json(new { Status = 1, Message = "File Imported Successfully " });
  16. }
  17. catch (Exception ex)
  18. {
  19. return Json(new { Status = 0, Message = ex.Message });
  20. }
  21. }
Here we are getting the file in HttpPostedFileBase format sent from Ajax call. We have called the method to read CSV file on Line 8 that we have created in Step 4. In Line 10 we have called extension method to convert the list into DataTable so we can send DataTable object as Sql Parameter.

Note
Extension method ToDataTable is not available in C#, as it's my own extension method. You can find the code for that method in Step 7 of the same article.
We have created Sql Parameter in Line 11 of type Structured. Type name isthe type of our table type object that we have created in my previous article. And we have called the stored procedure at Line 17.
Step 7
Extension method to convert the List object into DataTable.
  1. public static class Extensions
  2. {
  3. public static DataTable ToDataTable<T>(this List<T> items)
  4. {
  5. DataTable dataTable = new DataTable(typeof(T).Name);
  6. //Get all the properties
  7. PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
  8. foreach (PropertyInfo prop in Props)
  9. {
  10. //Defining type of data column gives proper data table
  11. var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
  12. //Setting column names as Property names
  13. dataTable.Columns.Add(prop.Name, type);
  14. }
  15. foreach (T item in items)
  16. {
  17. var values = new object[Props.Length];
  18. for (int i = 0; i < Props.Length; i++)
  19. {
  20. //inserting property values to datatable rows
  21. values[i] = Props[i].GetValue(item, null);
  22. }
  23. dataTable.Rows.Add(values);
  24. }
  25. return dataTable;
  26. }
  27. }
Step 8
We have implemented the functionality, and now we will launch the application and see the output. After launching the application goes to the below URL:

https://localhost:<Port Number>/Employee/Index and you will be able to see the below output.
Import Excel File To SQL Table In ASP.NET MVC
Now select the CSV file that we have created in Step 4 and click on upload. Once the file upload is completed you will get an alert message.
Thanks for reading this article. Let me know your feedback to enhance the quality of the article.