Import Data From Excel File to Database Table in ASP.Net MVC 4

My previous article explained how to export data from a database table to an Excel file. This article provides a brief introduction to importing data from an Excel file to a database. There are many ways to import data from Excel to a SQL Server database and here I'm going to introduce one simple common method to import data into a data table.

To begin, you need to create a database for storing data in the data table. The design of the database table looks like the following.



First of all open Visual Studio 2012 then select New project and click on ASP.NET MVC4 Web Application in Visual C#. Name the project ImportToExcel or whatever you like.

Create a controller named HomeController and in this controller create an Action Result method named Index.

  1. public ActionResult Index()  
  2. {  
  3.      return View();  
  4. } 
Now create a view, right-click on the Indexaction method and select Add View and then click OK. Add a file uploader control to the Index.cshtml page to upload an Excel file or write the following code to the view for displaying the data.
  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6. @using (Html.BeginForm("Index","Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  7. {   
  8. <input type="file" name="file" />  
  9.     <input type="submit" value="OK" />  
  10. } 
Now create a httppost method for the Index.cshtml page for getting an uploaded file on the controller. Now write the code to read the uploaded file. Here I'm using the OledbConnection to connect to the Excel Sheet. There are two types of connection strings for an Excel file, the fist for a ”.xls” file and the second is for a “.xlsx” file.

Write the connection string for the “.xls” file as in the following:
  1. excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
And the connection sting for a “.xlsx” file as in the following:
  1. excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  
Now get the data from the Excel file and insert it into the DataTable. After it inserts into the DataTable in the database, or write the following code in the httppost method.
  1. [HttpPost]  
  2. public ActionResult Index(HttpPostedFileBase file)  
  3. {  
  4.     DataSet ds = new DataSet();  
  5.     if (Request.Files["file"].ContentLength > 0)  
  6.     {  
  7.         string fileExtension =  
  8.                              System.IO.Path.GetExtension(Request.Files["file"].FileName);  
  9.         if (fileExtension == ".xls" || fileExtension == ".xlsx")  
  10.         {  
  11.             string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;  
  12.             if (System.IO.File.Exists(fileLocation))  
  13.             {  
  14.                 System.IO.File.Delete(fileLocation);  
  15.             }  
  16.             Request.Files["file"].SaveAs(fileLocation);  
  17.             string excelConnectionString = string.Empty;  
  18.             excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  
  19.             //connection String for xls file format.  
  20.             if (fileExtension == ".xls")  
  21.             {  
  22.                 excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";  
  23.             }  
  24.             //connection String for xlsx file format.  
  25.             else if (fileExtension == ".xlsx")  
  26.             {  
  27.                 excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  
  28.             }  
  29.             //Create Connection to Excel work book and add oledb namespace  
  30.             OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);  
  31.             excelConnection.Open();  
  32.             DataTable dt = new DataTable();  
  33.   
  34.             dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  
  35.             if (dt == null)  
  36.             {  
  37.                 return null;  
  38.             }  
  39.             String[] excelSheets = new String[dt.Rows.Count];  
  40.             int t = 0;  
  41.             //excel data saves in temp file here.  
  42.             foreach (DataRow row in dt.Rows)  
  43.             {  
  44.                 excelSheets[t] = row["TABLE_NAME"].ToString();  
  45.                 t++;  
  46.             }  
  47.             OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);  
  48.   
  49.             string query = string.Format("Select * from [{0}]", excelSheets[0]);  
  50.             using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))  
  51.             {  
  52.                 dataAdapter.Fill(ds);  
  53.             }  
  54.         }  
  55.         if (fileExtension.ToString().ToLower().Equals(".xml"))  
  56.         {  
  57.             string fileLocation = Server.MapPath("~/Content/") + Request.Files["FileUpload"].FileName;  
  58.             if (System.IO.File.Exists(fileLocation))  
  59.             {  
  60.                 System.IO.File.Delete(fileLocation);  
  61.             }  
  62.   
  63.             Request.Files["FileUpload"].SaveAs(fileLocation);  
  64.             XmlTextReader xmlreader = new XmlTextReader(fileLocation);  
  65.             // DataSet ds = new DataSet();  
  66.             ds.ReadXml(xmlreader);  
  67.             xmlreader.Close();  
  68.         }  
  69.         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
  70.         {  
  71.             string conn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;  
  72.             SqlConnection con = new SqlConnection(conn);  
  73.             string query = "Insert into Person(Name,Email,Mobile) Values('" + ds.Tables[0].Rows[i][0].ToString() + "','" + ds.Tables[0].Rows[i][1].ToString() + "','" + ds.Tables[0].Rows[i][2].ToString() + "')";  
  74.             con.Open();  
  75.             SqlCommand cmd = new SqlCommand(query, con);  
  76.             cmd.ExecuteNonQuery();  
  77.             con.Close();  
  78.         }  
  79.     }  
  80.     return View();  
  81. }
Now build and run your application.



Choose an Excel file to import data into the database. Ensure that your database table columns and Excel file columns are the same.





Click on the “OK” button to upload the file. If you have any issue or query then feel free to contact me.


Similar Articles