In this article I will explain with an example, how to import (insert) Excel file data into Database using SqlBulkCopy in ASP.Net Core MVC.
The uploaded Excel file data will be read using OLEDB library and the read data will be inserted into SQL Server database using SqlBulkCopy.
SqlBulkCopy class as the name suggests does bulk insert from one source to another and hence all rows from the Excel sheet can be easily read and inserted using the SqlBulkCopy class.
Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
 
 
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
.Net Core: Import (Insert) Excel file data into Database ASP.Net Core MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Downloading System.Data.OleDb Package from NuGet
You will need to install the System.Data.OleDb package using the following command.
Install-Package System.Data.OleDb -Version 4.7.1
 
 
Downloading and installing Microsoft.ACE.OLEDB.12.0 provider
You will need to download and install the Microsoft.ACE.OLEDB.12.0 provider using the following link.
 
 
Connection Strings in AppSettings.json file
The connection string to the Database and Excel file are saved in the AppSettings.json file.
Note: For more details about saving and reading connection strings in AppSettings.json file, please refer .Net Core: Read Connection String from AppSettings.json file.
 
The DataSource property has been assigned a Placeholder {0}, which will be replaced by actual path of the File.
{
 "ConnectionStrings": {
    "constr": "Data Source=.\\SQL2017;Initial Catalog=AjaxSamples;Integrated Security=true",
    "ExcelConString": "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"
 }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for uploading and reading Excel file
This Action method gets called when the Excel File is selected and the Import Button is clicked, and it gets the uploaded file in the IFormFile parameter.
Note: In case the HttpPostedFileBase parameter is appearing NULL, then please refer the article, ASP.Net Core: IFormFile always returns NULL.
 
The uploaded Excel file is saved to a folder named Uploads and then connection string is read from the Web.Config file and Placeholder is replaced by the path of the Excel file.
Note: For more details about IHostingEnvironment interface, please refer Using IHostingEnvironment in ASP.Net Core.
 
Using the fetched Sheet name, a SELECT statement is executed and all the records from the Excel sheet are fetched into a DataTable.
Note: I am considering all Excel files with the first row as the Header Row containing the names of the columns, you can set HDR=’No’ if your excel file does not have a Header Row.
 
Now a connection is established with the database and the SqlBulkCopy object is initialized and I have specified the name of the Table using the DestinationTableName property.
Finally the columns are mapped and all the rows from the DataTable are inserted into the SQL Server table.
Note: The mapping of columns of the DataTable and the SQL Server table is optional and you need to do only in case where your DataTable and/or the SQL Server Table do not have same number of columns or the names of columns are different.
 
public class HomeController : Controller
{
    private IHostingEnvironment Environment;
    private IConfiguration Configuration;
    public HomeController(IHostingEnvironment _environment, IConfiguration _configuration)
    {
        Environment = _environment;
        Configuration = _configuration;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(IFormFile postedFile)
    {
        if (postedFile != null)
        {
            //Create a Folder.
            string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
 
            //Save the uploaded Excel file.
            string fileName = Path.GetFileName(postedFile.FileName);
            string filePath = Path.Combine(path, fileName);
            using (FileStream stream = new FileStream(filePath, FileMode.Create))
            {
                postedFile.CopyTo(stream);
            }
 
            //Read the connection string for the Excel file.
            string conString = this.Configuration.GetConnectionString("ExcelConString");
            DataTable dt = new DataTable();
            conString = string.Format(conString, filePath);
 
            using (OleDbConnection connExcel = new OleDbConnection(conString))
            {
                using (OleDbCommand cmdExcel = new OleDbCommand())
                {
                    using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                    {
                        cmdExcel.Connection = connExcel;
 
                        //Get the name of First Sheet.
                        connExcel.Open();
                        DataTable dtExcelSchema;
                        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        connExcel.Close();
 
                        //Read Data from First Sheet.
                        connExcel.Open();
                        cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
                        odaExcel.SelectCommand = cmdExcel;
                        odaExcel.Fill(dt);
                        connExcel.Close();
                    }
                }
            }
 
            //Insert the Data read from the Excel file to Database Table.
            conString = this.Configuration.GetConnectionString("constr");
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.Customers";
 
                    //[OPTIONAL]: Map the Excel columns with that of the database table.
                    sqlBulkCopy.ColumnMappings.Add("Id", "CustomerId");
                    sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                    sqlBulkCopy.ColumnMappings.Add("Country", "Country");
 
                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                }
            }
        }
 
        return View();
    }
}
 
 
View
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of an HTML FileUpload element and a Submit Button.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form asp-controller="Home" asp-action="Index" method="post" enctype="multipart/form-data">
        <input type="file" name="postedFile"/>
        <input type="submit" value="Import"/>
    </form>
</body>
</html>
 
 
Screenshots
The Excel File
.Net Core: Import (Insert) Excel file data into Database ASP.Net Core MVC
 
Table containing the data from the Excel file
.Net Core: Import (Insert) Excel file data into Database ASP.Net Core MVC
 
 
Downloads