Inserting Excel File Records Into SQL Server Database Using ASP.Net C#

 Background

I have often read the common question in forum posts, how to upload Excel file records into a database but no one has provided the proper solution and many solutions contain a lot of code that is not required so by considering the preceding requirements I have decided to write this article to provide the solution to insert Excel file records into the database with a minimum amount of code. So let us start creating an application so beginners can also understand.
 
First create the table named Employee using the following script:
  1. CREATE TABLE [dbo].[Employee](  
  2.     [id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [City] [varchar](50) NULL,  
  5.     [Address] [varchar](50) NULL,  
  6.     [Designation] [varchar](50) NULL,  
  7.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [id] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  11. ON [PRIMARY
Then the design view of the table will look such as follows:
 
 
Create the same Excel file with the following records:
 
 
 
Now Let us create the sample web application as follows:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
  3. Provide the web site a name such as "InsertExcelFileIntoDataBase" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
  5. Drag and drop one Button and FileUploader controler onto the <form> section of the Default.aspx page.

Now the default.aspx Page source code will look such as follows.

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>    
  2.     
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">    
  4. <html xmlns="http://www.w3.org/1999/xhtml">    
  5. <head id="Head1" runat="server">    
  6.     <title>Article by Vithal Wadje</title>    
  7. </head>    
  8. <body bgcolor="blue">    
  9.     <form id="form1" runat="server">    
  10.     <div style="color: White;">    
  11.         <h4>    
  12.             Article for C#Corner    
  13.         </h4>    
  14.         <table>    
  15.             <tr>    
  16.                 <td>    
  17.                     Select File    
  18.                 </td>    
  19.                 <td>    
  20.                     <asp:FileUpload ID="FileUpload1" runat="server" />    
  21.                 </td>    
  22.                 <td>    
  23.                 </td>    
  24.                 <td>    
  25.                     <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />    
  26.                 </td>    
  27.             </tr>    
  28.         </table>    
  29.     </div>    
  30.     </form>    
  31. </body>    
  32. </html>  
Now open the Default.aspx.cs page and write the following code to create an oledbconnection for the Excel file as in the following:
  1. private void ExcelConn(string FilePath)    
  2. {  
  3.     constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);    
  4.     Econ = new OleDbConnection(constr);       
  5. } 
Create a function for Sqlconnection as:
  1. private void connection()    
  2. {    
  3.     sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;    
  4.     con = new SqlConnection(sqlconn);  
  5. } 
Create a function to read and insert an Excel File into the database as:
  1. private void InsertExcelRecords(string FilePath)    
  2. {    
  3.     ExcelConn(FilePath);  
  4.     Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]""Sheet1$");    
  5.     OleDbCommand Ecom = new OleDbCommand(Query, Econ);    
  6.     Econ.Open();    
  7.     DataSet ds=new DataSet();    
  8.     OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);    
  9.     Econ.Close();    
  10.     oda.Fill(ds);    
  11.    DataTable Exceldt = ds.Tables[0];    
  12.    connection();    
  13.    //creating object of SqlBulkCopy      
  14.    SqlBulkCopy objbulk = new SqlBulkCopy(con);    
  15.    //assigning Destination table name      
  16.    objbulk.DestinationTableName = "Employee";    
  17.    //Mapping Table column      
  18.    objbulk.ColumnMappings.Add("Name""Name");    
  19.    objbulk.ColumnMappings.Add("City""City");    
  20.    objbulk.ColumnMappings.Add("Address""Address");    
  21.    objbulk.ColumnMappings.Add("Designation""Designation");    
  22.    //inserting Datatable Records to DataBase      
  23.    con.Open();    
  24.    objbulk.WriteToServer(Exceldt);    
  25.    con.Close();    
  26. } 
Now call the preceding function on the button click as:
  1. protected void Button1_Click(object sender, EventArgs e)    
  2. {    
  3.     string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);    
  4.     InsertExcelRecords(CurrentFilePath);    
  5. } 
The entire code of the default.aspx.cs page will look as follows:
  1. using System;  
  2. using System.Data;  
  3. using System.IO;  
  4. using System.Data.OleDb;  
  5. using System.Configuration;  
  6. using System.Data.SqlClient;  
  7.   
  8. public partial class _Default : System.Web.UI.Page  
  9. {  
  10.     OleDbConnection Econ;  
  11.     SqlConnection con;  
  12.   
  13.     string constr,Query,sqlconn;  
  14.     protected void Page_Load(object sender, EventArgs e)  
  15.     {
  16.     }  
  17.   
  18.     private void ExcelConn(string FilePath)  
  19.     {  
  20.   
  21.         constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);  
  22.         Econ = new OleDbConnection(constr);  
  23.        
  24.     }  
  25.     private void connection()  
  26.     {  
  27.         sqlconn = ConfigurationManager.ConnectionStrings["SqlCom"].ConnectionString;  
  28.         con = new SqlConnection(sqlconn);  
  29.       
  30.     }
  31.     private void InsertExcelRecords(string FilePath)  
  32.     {  
  33.         ExcelConn(FilePath);  
  34.   
  35.         Query = string.Format("Select [Name],[City],[Address],[Designation] FROM [{0}]""Sheet1$");  
  36.         OleDbCommand Ecom = new OleDbCommand(Query, Econ);  
  37.         Econ.Open();  
  38.   
  39.         DataSet ds=new DataSet();  
  40.         OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);  
  41.         Econ.Close();  
  42.         oda.Fill(ds);  
  43.         DataTable Exceldt = ds.Tables[0];  
  44.         connection();  
  45.         //creating object of SqlBulkCopy    
  46.         SqlBulkCopy objbulk = new SqlBulkCopy(con);  
  47.         //assigning Destination table name    
  48.         objbulk.DestinationTableName = "Employee";  
  49.         //Mapping Table column    
  50.         objbulk.ColumnMappings.Add("Name""Name");  
  51.         objbulk.ColumnMappings.Add("City""City");  
  52.         objbulk.ColumnMappings.Add("Address""Address");  
  53.         objbulk.ColumnMappings.Add("Designation""Designation");  
  54.         //inserting Datatable Records to DataBase    
  55.         con.Open();  
  56.         objbulk.WriteToServer(Exceldt);  
  57.         con.Close();
  58.     }  
  59.     protected void Button1_Click(object sender, EventArgs e)  
  60.     {   
  61.         string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
  62.         InsertExcelRecords(CurrentFilePath);  
  63.     }  

Now run the application and upload the file as follows:
 
 
 
Now click on the Upload button and see the records in the database table as:
 
 
 
Now you have seen how the records are inserted into the database with minimal code and effort.
 
Notes
  • For detailed code please download the sample Zip file.

  • Do a proper validation such as date input values when implementing.

  • Make the changes in the web.config file depending on your server details for the connection string.
Summary

From all the preceding examples you have learned how to insert Excel records into the database. I hope this article is useful for all readers, if you have a suggestion then please contact me.


Similar Articles