Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Import Data from Excel File to Database Table in ASP.NET MVC 4

0.00/5 (No votes)
1 Apr 2014 4  
This tip introduces how to Import data From Excel file to Data Table in ASP.NET MVC4

Introduction

My previous article discussed about how to Export data from database table to Excel file. Now in this article, I’ve covered a brief introduction about importing data from Excel File to database. There are lots of ways for Importing data from Excel to SQL server database, and here I’m going to introduce one simple common method to import data into data table.

Using the Code

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

First of all, open Visual Studio 2012. After that, select new project and click on ASP.NET MVC4 Web Application in Visual C#, name the project ImportToExcel and whatever you like. Create a controller named HomeController and in this controller, create an Action Result method named Index.

           public ActionResult Index()
        {
            return View();
        }   

Now, create a view, right click on the Indexaction method and select Add View and then click OK. Add a file uploader control in Index.cshtml page for upload Excel file or write the following code to the view for display data.

 @{
    ViewBag.Title = "Index";
}

<h2>
    Index</h2>
@using (Html.BeginForm("Index","Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
<input type="file" name="file" />
    <input type="submit" value="OK" />
}  

Now create httppost method for Index.cshtml page for get uploaded file on controller. Now write the code for read uploaded file. Here I’m using the OledbConnection to connect to the Excel Sheet. There are two types of connection strings for Excel file fist for”.xls” file and second is “.xlsx” file.

Write the connection string for “.xls” file:

 excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
    fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";  

And the connection sting for “.xlsx” file is:

  excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
    fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  

Now get the data from Excel file and insert it into a DataTable. After that, insert DataTable to database or write the following code in the httppost method:

  [HttpPost]
        public ActionResult Index(HttpPostedFileBase file)
        {
            DataSet ds = new DataSet();
            if (Request.Files["file"].ContentLength > 0)
            {
                string fileExtension =
                                     System.IO.Path.GetExtension(Request.Files["file"].FileName);

                if (fileExtension == ".xls" || fileExtension == ".xlsx")
                {
                    string fileLocation = Server.MapPath("~/Content/") + Request.Files["file"].FileName;
                    if (System.IO.File.Exists(fileLocation))
                    {

                        System.IO.File.Delete(fileLocation);
                    }
                    Request.Files["file"].SaveAs(fileLocation);
                    string excelConnectionString = string.Empty;
                    excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
                    fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    //connection String for xls file format.
                    if (fileExtension == ".xls")
                    {
                        excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
                        fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    }
                    //connection String for xlsx file format.
                    else if (fileExtension == ".xlsx")
                    {
                        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + 
                        fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    }
                    //Create Connection to Excel work book and add oledb namespace
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                    excelConnection.Open();
                    DataTable dt = new DataTable();

                    dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    if (dt == null)
                    {
                        return null;
                    }

                    String[] excelSheets = new String[dt.Rows.Count];
                    int t = 0;
                    //excel data saves in temp file here.
                    foreach (DataRow row in dt.Rows)
                    {
                        excelSheets[t] = row["TABLE_NAME"].ToString();
                        t++;
                    }
                    OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);


                    string query = string.Format("Select * from [{0}]", excelSheets[0]);
                    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                    {
                        dataAdapter.Fill(ds);
                    }
                }
                if (fileExtension.ToString().ToLower().Equals(".xml"))
                {
                    string fileLocation = Server.MapPath("~/Content/") + Request.Files["FileUpload"].FileName;
                    if (System.IO.File.Exists(fileLocation))
                    {
                        System.IO.File.Delete(fileLocation);
                    }

                    Request.Files["FileUpload"].SaveAs(fileLocation);
                    XmlTextReader xmlreader = new XmlTextReader(fileLocation);
                    // DataSet ds = new DataSet();
                    ds.ReadXml(xmlreader);
                    xmlreader.Close();
                }

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string conn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
                    SqlConnection con = new SqlConnection(conn);
                    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() + "')";
                    con.Open();
                    SqlCommand cmd = new SqlCommand(query, con);
                    cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            return View();
        }   

Now build and run your application.

Chose an Excel file for import data in database. Ensure that your database table columns and Excel file columns should be the same.

Click on “OK” button for upload file. If you have any issues and queries, then feel free to contact me.

History

  • 31st March, 2014: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here