Asp.Net: Import excel sheet data in GridView and insert it into Database using asp.net c#

Step 1: File Upload control 
  1. <label class="control-label">  
  2. Select an Excel File</label>  
  3. <div class="controls">  
  4.     <asp:UpdatePanel ID="UpdatePanel2" runat="server">  
  5.         <ContentTemplate>  
  6.             <asp:FileUpload ID="FileUpload1" class="default" runat="server" accept=".xlsx,.xls,.csv" />  
  7.             <asp:Label ID="lbl" runat="server"></asp:Label>  
  8.         </ContentTemplate>  
  9.     </asp:UpdatePanel>  
Step 2: Add GridView with excel sheet datafields 
  1. <asp:Panel ID="Panel1" runat="server" ScrollBars="Both" Height="400px">  
  2.     <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
  3.         <ContentTemplate>  
  4.             <div id="GHead">  
  5.             </div>  
  6.             <asp:GridView ID="gvExcelFile" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" class="table table-striped table-bordered table-hover" AutoGenerateColumns="False" AllowSorting="True" ShowHeader="true">  
  7.                 <Columns>  
  8.                    
  9.                     <asp:BoundField DataField="Date" DataFormatString="{0:dd/MM/yyyy}" HeaderText="Meeting Date" />  
  10.                     <asp:BoundField DataFormatString="{0:HH:mm tt}" DataField="Meeting Time" HeaderText="Meeting Time" />  
  11.                     <asp:BoundField DataField="Location" HeaderText="Location" />  
  12.                     <asp:BoundField DataField="BDM Name" HeaderText="BDM Name" />  
  13.                     <asp:BoundField DataField="Company Name" HeaderText="Company Name" />  
  14.                     <asp:BoundField DataField="Customer Name" HeaderText="Customer Name" />  
  15.                     <asp:BoundField DataField="Full Address" HeaderText="Full Address" Visible="" />  
  16.                     <asp:BoundField DataField="Contact Number" HeaderText="Contact Number" Visible="" />  
  17.                     <asp:BoundField DataField="Email ID" HeaderText="Email ID" Visible="" />  
  18.                    
  19.                 </Columns>  
  20.             </asp:GridView>  
  21.         </ContentTemplate>  
  22.     </asp:UpdatePanel>  
  23. </asp:Panel>  
  24. <asp:Button ID="btnSubmit" class="btn blue" runat="server" ValidationGroup="save" Text="Save" OnClick="btnSubmit_Click" />   
-->Grid for duplicate records
  1. <asp:GridView ID="GridView1" CellPadding="4" ForeColor="#333333" class="table table-striped table-bordered table-hover" runat="server" AutoGenerateColumns="False" >  
  2.     <Columns>  
  3.         <asp:TemplateField HeaderText="Designation_id" Visible="False">  
  4.             <EditItemTemplate>  
  5.                 <asp:Label ID="lblEditDesignationid" runat="server" Text='<%# Bind("Dmr_id") %>'></asp:Label>  
  6.             </EditItemTemplate>  
  7.             <ItemTemplate>  
  8.                 <asp:Label ID="lblDesignationid" runat="server" Text='<%# Bind("Dmr_id") %>'></asp:Label>  
  9.             </ItemTemplate>  
  10.         </asp:TemplateField>  
  11.         <asp:TemplateField HeaderText="Meeting Date">  
  12.             <EditItemTemplate>  
  13.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Meeting_date") %>'></asp:TextBox>  
  14.             </EditItemTemplate>  
  15.             <ItemTemplate>  
  16.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Meeting_date") %>'></asp:Label>  
  17.             </ItemTemplate>  
  18.         </asp:TemplateField>  
  19.         <asp:TemplateField HeaderText="Meeting Time">  
  20.             <EditItemTemplate>  
  21.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Meeting_time") %>'></asp:TextBox>  
  22.             </EditItemTemplate>  
  23.             <ItemTemplate>  
  24.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Meeting_time") %>'></asp:Label>  
  25.             </ItemTemplate>  
  26.         </asp:TemplateField>  
  27.         <asp:TemplateField HeaderText="Location">  
  28.             <EditItemTemplate>  
  29.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Location") %>'></asp:TextBox>  
  30.             </EditItemTemplate>  
  31.             <ItemTemplate>  
  32.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Location") %>'></asp:Label>  
  33.             </ItemTemplate>  
  34.         </asp:TemplateField>  
  35.         <asp:TemplateField HeaderText="BDM Name">  
  36.             <EditItemTemplate>  
  37.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("User_id") %>'></asp:TextBox>  
  38.             </EditItemTemplate>  
  39.             <ItemTemplate>  
  40.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("User_id") %>'></asp:Label>  
  41.             </ItemTemplate>  
  42.         </asp:TemplateField>  
  43.         <asp:TemplateField HeaderText="Company Name">  
  44.             <EditItemTemplate>  
  45.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Company_name") %>'></asp:TextBox>  
  46.             </EditItemTemplate>  
  47.             <ItemTemplate>  
  48.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Company_name") %>'></asp:Label>  
  49.             </ItemTemplate>  
  50.         </asp:TemplateField>  
  51.         <asp:TemplateField HeaderText="Customer Name">  
  52.             <EditItemTemplate>  
  53.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Cutomer_name") %>'></asp:TextBox>  
  54.             </EditItemTemplate>  
  55.             <ItemTemplate>  
  56.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Cutomer_name") %>'></asp:Label>  
  57.             </ItemTemplate>  
  58.         </asp:TemplateField>  
  59.         <asp:TemplateField HeaderText="Address">  
  60.             <EditItemTemplate>  
  61.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>  
  62.             </EditItemTemplate>  
  63.             <ItemTemplate>  
  64.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Address") %>'></asp:Label>  
  65.             </ItemTemplate>  
  66.         </asp:TemplateField>  
  67.         <asp:TemplateField HeaderText="Contact Number">  
  68.             <EditItemTemplate>  
  69.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Contact") %>'></asp:TextBox>  
  70.             </EditItemTemplate>  
  71.             <ItemTemplate>  
  72.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Contact") %>'></asp:Label>  
  73.             </ItemTemplate>  
  74.         </asp:TemplateField>  
  75.         <asp:TemplateField HeaderText="Email ID">  
  76.             <EditItemTemplate>  
  77.                 <asp:TextBox ID="txtEditDesignationName" runat="server" Text='<%# Bind("Email_id") %>'></asp:TextBox>  
  78.             </EditItemTemplate>  
  79.             <ItemTemplate>  
  80.                 <asp:Label ID="lblDesignationName" runat="server" Text='<%# Bind("Email_id") %>'></asp:Label>  
  81.             </ItemTemplate>  
  82.         </asp:TemplateField>  
  83.        
  84.     </Columns>  
  85. </asp:GridView>   
Step 3: Add Java Script to load excel sheet data into GridView
  1. <script type="text/javascript">  
  2.     function UploadFile(fileUpload)  
  3.     {  
  4.         if (fileUpload.value != '')  
  5.         {  
  6.             document.getElementById("<%=LinkButton1.ClientID %>").click();  
  7.         }  
  8.     }  
  9. </script>   
Step 4: Add LinkButton 
  1. <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click"></asp:LinkButton>   
C# Coding 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.IO;  
  9. using System.Data.OleDb;  
  10. using System.Drawing;  
  11. using System.Globalization;  
  12.   
  13.   
  14. public partial class Dmr_Excel: System.Web.UI.Page  
  15. {  
  16.   
  17.     clsConnection c1 = new clsConnection();  
  18.     protected void Page_Load(object sender, EventArgs e)  
  19.     {  
  20.         if (!IsPostBack)  
  21.         {  
  22.  
  23.             FileUpload1.Attributes["onchange"] = "UploadFile(this)";  
  24.             
  25.         }  
  26.     }  
  27.  
  28.     DataTable dt_duplicate_row = new DataTable();  
  29.   
  30.     private void FillDates()  
  31.     {  
  32.         DateTime CurrentDate = DateTime.Today;  
  33.         var lastDayOfMonth = DateTime.DaysInMonth(CurrentDate.Year, CurrentDate.Month);  
  34.     }  
  35.     private void Upload_data()  
  36.     {  
  37.   
  38.   
  39.         if (dt_duplicate_row.Columns.Count == 0)  
  40.         {  
  41.             dt_duplicate_row.Columns.Add("Date");  
  42.             dt_duplicate_row.Columns.Add("Meeting Time");  
  43.             dt_duplicate_row.Columns.Add("Location");  
  44.             dt_duplicate_row.Columns.Add("BDM Name");  
  45.             dt_duplicate_row.Columns.Add("Company Name");  
  46.             dt_duplicate_row.Columns.Add("Customer Name");  
  47.             dt_duplicate_row.Columns.Add("Full Address");  
  48.             dt_duplicate_row.Columns.Add("Contact Number");  
  49.             dt_duplicate_row.Columns.Add("Email Id");  
  50.            
  51.         }  
  52.   
  53.         foreach(GridViewRow grd in gvExcelFile.Rows)  
  54.         {  
  55.             string date = grd.Cells[1].Text;  
  56.             string Meet_date = grd.Cells[1].Text;  
  57.             string meeting_time = grd.Cells[2].Text;  
  58.             string location = grd.Cells[3].Text;  
  59.             string bdm_name = grd.Cells[4].Text;  
  60.             string Company_name = grd.Cells[5].Text;  
  61.             string Customer_name = grd.Cells[6].Text;  
  62.             string address = grd.Cells[7].Text;  
  63.             string contact_no = grd.Cells[8].Text;  
  64.             string email_id = grd.Cells[9].Text;  
  65.            
  66.             int City_id = 1;  
  67.             string f_date = "";  
  68.   
  69.   
  70.             location = location.Replace("'""~");  
  71.             bdm_name = bdm_name.Replace("'""~");  
  72.             Customer_name = Customer_name.Replace("'""~");  
  73.             Company_name = Company_name.Replace("'""~");  
  74.             address = address.Replace("'""~");  
  75.             email_id = email_id.Replace("'""~");  
  76.             package = package.Replace("'""~");  
  77.             remark = remark.Replace("'""~");  
  78.             call_type = call_type.Replace("'""~");  
  79.             visting_card = visting_card.Replace("'""~");  
  80.   
  81.             if (date == " " && Meet_date == " " && meeting_time == " " && location == " " && bdm_name == " " && Company_name == " " &&  
  82.                 Customer_name == " " && address == " " && contact_no == " " && email_id == " " )  
  83.             {  
  84.                 continue;  
  85.             }  
  86.   
  87.   
  88.             if (date == "NA" || date == "" || date == " " || date == null)  
  89.             {  
  90.                 dt_duplicate_row.Rows.Add(Meet_date, meeting_time, location, bdm_name, Company_name, Customer_name, address, contact_no,  
  91.                     email_id);  
  92.                 continue;  
  93.             } else   
  94.             {  
  95.                 Meet_date = Convert.ToDateTime(date).ToString("yyyy-MM-dd");  
  96.             }  
  97.             if (amount == "" || amount == " " || amount == null)   
  98.             {  
  99.                 amount = "0";  
  100.             }  
  101.            
  102.             string str = "Select * from dmr_login where Meeting_date='" + Meet_date + "' and Contact_no='" + contact_no + "' ";  
  103.             DataTable dt_check = c1.filldt(str);  
  104.             if (dt_check.Rows.Count > 0)  
  105.             {  
  106.                 dt_duplicate_row.Rows.Add(Meet_date, meeting_time, location, bdm_name, Company_name, Customer_name, address, contact_no,  
  107.                     email_id);  
  108.   
  109.             } else  
  110.             {  
  111.                 DateTime dts = Convert.ToDateTime(Meet_date);  
  112.                 FillDays(dts);  
  113.                 CultureInfo ci = new CultureInfo("en-US");  
  114.                 string Month_name = dts.ToString("MMMM", ci);  
  115.                 string Year_name = dts.ToString("yyyy");  
  116.                 string dmr_insert = "Insert into dmr_login (User_id,Meeting_date,Meeting_time,Location,City_id,Company_name,Customer_name,Address,";  
  117.                 dmr_insert += " Contact_no,Email_id,Record_month,Record_year) values (";  
  118.                 dmr_insert += " " + ddluser.SelectedValue + ",'" + Meet_date + "','" + meeting_time + "','" + location + "'," + City_id + ",'" + Company_name + "','" + Customer_name + "',";  
  119.                 dmr_insert += " '" + address + "','" + contact_no + "','" + email_id + "','" + DateTime.Now.ToString("yyyy-MM-dd") + "','" + Month_name + "','" + Year_name + "')";  
  120.                 c1.IUD(dmr_insert);  
  121.                 if (clsConnection.z == 1)  
  122.                 {  
  123.                     clsConnection.z = 0;  
  124.                 }  
  125.             
  126.   
  127.         } 

  128.         if (dt_duplicate_row.Rows.Count > 0)  
  129.         {  
  130.   
  131.             lblMsg.Text = "Record Saved Successfully";  
  132.             PanelMsg.Visible = true;  
  133.             lblErrorMsg.Text = "Duplicate Record Found";  
  134.             PanelErrorMsg.Visible = true;  
  135.             btnExportExcel.Visible = true;  
  136.             btnSubmit.Visible = false;  
  137.   
  138.         } 
  139.     else   
  140.         {  
  141.             lblErrorMsg.Text = "Duplicate Record Found";  
  142.             PanelErrorMsg.Visible = false;  
  143.         }  
  144.         gvExcelFile.DataSource = dt_duplicate_row;  
  145.         clsVariable.dt_duplicate = dt_duplicate_row.Clone();  
  146.         clsVariable.dt_duplicate = dt_duplicate_row.Copy();  
  147.         gvExcelFile.DataBind();  
  148.         lblMsg.Text = "Record Saved Successfully";  
  149.         PanelMsg.Visible = true;  
  150.     }  
  151.    
  152.     protected void SaveExcelData()  
  153.     {  
  154.         for (int i = 0; i < gvExcelFile.Rows.Count; i++)   
  155.         {  
  156.   
  157.             GridViewRow row = gvExcelFile.Rows[i];  
  158.             CheckBox chkbox = (CheckBox) row.FindControl("chbView");  
  159.   
  160.   
  161.             string Date = row.Cells[1].Text;  
  162.             string Meet_date = "";  
  163.             // string Follow_date = "";  
  164.   
  165.             if (Date == "NA" || Date == " " || Date == "")   
  166.             {  
  167.                 continue;  
  168.             } else  
  169.             {  
  170.                 Meet_date = Convert.ToDateTime(Date).ToString("dd-MM-yyyy");  
  171.             }  
  172.             string Meeting_time = row.Cells[2].Text;  
  173.             string Location = row.Cells[3].Text;  
  174.             if (Location == " ")  
  175.             {  
  176.                 return;  
  177.             }  
  178.   
  179.             string usrname = "select * from tbl_user where User_name='" + ddluser.SelectedValue + "'";  
  180.             DataTable user_name = c1.filldt(usrname);  
  181.             int b = 1;  
  182.             if (user_name.Rows.Count > 0)   
  183.             {  
  184.                 b = Convert.ToInt32(user_name.Rows[0]["User_id"].ToString());  
  185.             }  
  186.   
  187.             string Company_name = row.Cells[5].Text;  
  188.             string Customer = row.Cells[6].Text;  
  189.   
  190.   
  191.   
  192.   
  193.             string Address = row.Cells[7].Text;  
  194.             string Contact_no = row.Cells[8].Text;  
  195.             string Email_id = row.Cells[9].Text;  
  196.   
  197.   
  198.   
  199.             string Package = row.Cells[10].Text;  
  200.             string Product = "select * from tbl_package where Package_name='" + Package + "'";  
  201.             DataTable package_name = c1.filldt(Product);  
  202.             int c = 1;  
  203.             if (package_name.Rows.Count > 0)  
  204.             {  
  205.                 c = Convert.ToInt32(package_name.Rows[0]["Package_id"].ToString());  
  206.             }  
  207.   
  208.   
  209.             string Amount = row.Cells[11].Text;  
  210.             if (Amount == "NA" || Amount == " " || Amount == "")   
  211.             {  
  212.                 continue;  
  213.             }  
  214.           
  215.   
  216.   
  217.             string check = "select * from dmr_loginn where Meeting_date='" + Meet_date + "' and Contact='" + row.Cells[8].Text + "'";  
  218.             DataTable dt_check = c1.filldt(check);  
  219.   
  220.             if (dt_check.Rows.Count > 0)   
  221.             {  
  222.   
  223.   
  224.                 dt_duplicate_row.Columns.Add("Meeting Date");  
  225.                 dt_duplicate_row.Columns.Add("Meeting Time");  
  226.                 dt_duplicate_row.Columns.Add("Location");  
  227.                 dt_duplicate_row.Columns.Add("BDM Name");  
  228.                 dt_duplicate_row.Columns.Add("Company Name");  
  229.                 dt_duplicate_row.Columns.Add("Customer Name");  
  230.                 dt_duplicate_row.Columns.Add("Full Address");  
  231.                 dt_duplicate_row.Columns.Add("Contact Number");  
  232.                 dt_duplicate_row.Columns.Add("Email Id");  
  233.                
  234.   
  235.                 dt_duplicate_row.Rows.Add(Meet_date, Meeting_time, Location, b, Company_name, Customer, Address, Contact_no, Email_id);  
  236.                 gvExcelFile.DataSource = dt_duplicate_row;  
  237.   
  238.                 gvExcelFile.DataBind();  
  239.                 btnExportExcel.Visible = true;  
  240.   
  241.             } 
  242.   
  243.   
  244.                     string dtr = "Insert into dmr_loginn(User_id,Meeting_date,Meeting_time,Location,User_id,Company_name,Cutomer_name,Address,Contact,Email_id,";  
  245.                     dtr += " Package,Amount,Remark,Call_type,Follow_up_date,Telly_self,Visiting_card,branch_name) values";  
  246.                     dtr += "('" + ddluser.SelectedValue + "', '" + Meet_date + "','" + Meeting_time + "','" + Location + "','" + b + "','" + Company_name + "','" + Customer + "','" + Address + "',";  
  247.                     dtr += " '" + Contact_no + "','" + Email_id + "')";  
  248.                     c1.IUD(dtr);  
  249.                
  250.   
  251.                 if (clsConnection.z == 1)   
  252.                 {  
  253.                     clsConnection.z = 0;  
  254.                     lblMsg.Text = "Record Saved Successfully";  
  255.                     PanelMsg.Visible = true;  
  256.                     PanelErrorMsg.Visible = false;  
  257.                 }  
  258.   
  259.             }  
  260.         }  
  261.     }  
  262.   
  263.  
  264.     protected void btnSubmit_Click(object sender, EventArgs e)   
  265.     {  
  266.         Upload_data();  
  267.          
  268.     }  
  269.  
  270.     private void Export_excel(DataTable dt)  
  271.     {  
  272.         Response.ClearContent();  
  273.         Response.Buffer = true;  
  274.         Response.AddHeader("content-disposition"string.Format("attachment; filename={0}""DMR.xls"));  
  275.         Response.ContentType = "application/ms-excel";  
  276.         //DataTable dt = BindDatatable();  
  277.         string str = string.Empty;  
  278.         foreach(DataColumn dtcol in dt.Columns)  
  279.         {  
  280.             Response.Write(str + dtcol.ColumnName);  
  281.             str = "\t";  
  282.         }  
  283.         Response.Write("\n");  
  284.         foreach(DataRow dr in dt.Rows)  
  285.         {  
  286.             str = "";  
  287.             for (int j = 0; j < dt.Columns.Count; j++)  
  288.             {  
  289.                 Response.Write(str + Convert.ToString(dr[j]));  
  290.                 str = "\t";  
  291.             }  
  292.             Response.Write("\n");  
  293.         }  
  294.         Response.End();  
  295.     }  
  296.     protected void btnExportExcel_Click(object sender, EventArgs e)  
  297.     {  
  298.         Export_excel(clsVariable.dt_duplicate);  
  299.   
  300.     }  
  301.     protected void Button2_Click(object sender, EventArgs e)  
  302.     {  
  303.         Upload_data();  
  304.     } 

  305.     protected void LinkButton1_Click(object sender, EventArgs e)  
  306.     {  
  307.         if (FileUpload1.HasFile)  
  308.         {  
  309.             clsVariable.dt_duplicate.Rows.Clear();  
  310.             clsVariable.dt_duplicate.Columns.Clear();  
  311.             //Coneection String by default empty   
  312.             string ConStr = "";  
  313.             //Extantion of the file upload control saving into ext because   
  314.             //there are two types of extation .xls and .xlsx of Excel   
  315.             string ext = Path.GetExtension(FileUpload1.FileName).ToString();  
  316.             //getting the path of the file   
  317.             string path = Server.MapPath("~/TempExcel/DMR/" + FileUpload1.FileName);  
  318.             //saving the file inside the MyFolder of the server   
  319.             FileUpload1.SaveAs(path);  
  320.             // Label1.Text = FileUpload1.FileName + "\'s Data showing into the GridView";  
  321.             //checking that extantion is .xls or .xlsx   
  322.             if (ext.Trim() == ".xls") {  
  323.                 //connection string for that file which extantion is .xls   
  324.                 ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";  
  325.             } else if (ext.Trim() == ".xlsx") {  
  326.                 //connection string for that file which extantion is .xlsx   
  327.                 ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";  
  328.             }  
  329.             //making query   
  330.             string query = "SELECT * FROM [Sheet1$]";  
  331.             //Providing connection   
  332.             OleDbConnection conn = new OleDbConnection(ConStr);  
  333.             //checking that connection state is closed or not if closed the   
  334.             //open the connection   
  335.             if (conn.State == ConnectionState.Closed)  
  336.             {  
  337.                 conn.Open();  
  338.             }  
  339.   
  340.             //create command object   
  341.             OleDbCommand cmd = new OleDbCommand(query, conn);  
  342.             // create a data adapter and get the data into dataadapter   
  343.             OleDbDataAdapter da = new OleDbDataAdapter(cmd);  
  344.             DataSet ds = new DataSet();  
  345.             //fill the Excel data to data set   
  346.             da.Fill(ds);  
  347.             //set data source of the grid view   
  348.             gvExcelFile.DataSource = ds.Tables[0];  
  349.             //binding the gridview   
  350.             gvExcelFile.DataBind();  
  351.             //close the connection   
  352.             conn.Close();  
  353.             // LinkButton1.Visible = false;  
  354.             gvExcelFile.Visible = true;  
  355.             lbl.Text = "";  
  356.             PanelMsg.Visible = false;  
  357.             PanelErrorMsg.Visible = false;  
  358.             btnExportExcel.Visible = false;  
  359.             btnSubmit.Visible = true;  
  360.         }  
  361.     }  
  362. }