In this article I will explain with an example, how to import (insert)
Excel file data into Database using
SqlBulkCopy in ASP.Net Core (.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.
Download System.Data.OleDb DLL
There are two ways you can download the System.Data.OleDb DLL.
Database
I have made use of the following table Customers with the schema as follows.
Note: You can download the database table SQL by clicking the download link below.
Connection Strings in AppSettings.json file
The connection string to the Database and
Excel file are saved in the
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=.\\SQL2022;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.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
This Action method gets called when Import Button is clicked, and it gets the uploaded file in the IFormFile parameter.
The path of the Uploads Folder (Directory) where uploaded Excel file will be saved is fetched using IWebHostEnvironemnt interface and if it does not exists then it is created using CreateDirectory method.
The uploaded Excel file is saved to a Folder (Directory) named Uploads and an object of DataTable is created.
Then, the connection string is read from the AppSettings.json file and Placeholder is replaced by the path of the Excel file.
After that, the data of the Excel file is read into a DataTable object using
OLEDB driver and
ADO.Net.
Now a connection is established with the database and the SqlBulkCopy object is initialized and the name of the Table is specified 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 IWebHostEnvironment Environment;
private IConfiguration Configuration;
public HomeController(IWebHostEnvironment _environment, IConfiguration _configuration)
{
this.Environment = _environment;
this.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 constr = this.Configuration.GetConnectionString("ExcelConString");
DataTable dt = new DataTable();
constr = string.Format(constr, filePath);
using (OleDbConnection connExcel = new OleDbConnection(constr))
{
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.
constr = this.Configuration.GetConnectionString("constr");
using (SqlConnection con = new SqlConnection(constr))
{
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("Customer Id", "CustomerId");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
sqlBulkCopy.ColumnMappings.Add("Country", "Country");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
return View();
}
}
View
HTML Markup
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.
Note: The Form element must be specified with enctype attribute and its value must be multipart/form-data, otherwise the IFormFile parameter will be NULL.
@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"e nctype="multipart/form-data">
<input type="file" name="postedFile" />
<input type="submit" value="Import" />
</form>
</body>
</html>
Screenshots
The Excel File
Table containing the data from the Excel file
Downloads