I want to restrict duplicates while uploading the excel data and to inform the user that the particular cell in excel contains duplicate value which is already exist in Database. I have researched online regarding this problem and know one of the way is to insert my excel data to a temp table, then compare the data with the destination table and return the duplicates back to the user so that he can fix them and re-upload the file. But i do not know how do that without a code example.. Or is there any other way to do it? I would really appreciate your help!
(Duplicates should be checked only in Student_ID(pk), the student can have the same Student_name, Student_class .If duplicate record is found, Message should display as:"User cannot upload the data to with duplicate values. Kindly remove the duplicate fields and re-upload."
I've already successfully done the importing part using SqlBulkCopy
**This is my importing excel file to database code**
protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName))); FileUpload1.PostedFile.SaveAs(path); OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"); OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", OleDbcon); OleDbDataAdapter ObjAdapter1 = new OleDbDataAdapter(cmd); OleDbcon.Open(); DbDataReader dr = cmd.ExecuteReader(); string con_str = @"Data Source=xx;Initial Catalog=BSS;Integrated Security=True"; SqlBulkCopy bulkinsert = new SqlBulkCopy(con_str); bulkinsert.DestinationTableName = "Student"; bulkinsert.WriteToServer(dr); OleDbcon.Close(); Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete); Label1.ForeColor = Color.Green; Label1.Text = "Successfully inserted"; FetchData(); } else { Label1.ForeColor = Color.Red; Label1.Text = "Please select the file"; } } public void FetchData() { SqlConnection con = new SqlConnection("xx";Initial Catalog=BSS;Integrated Security=True"); SqlCommand cmd = new SqlCommand("select * from Student", con); con.Open(); SqlDataReader rdr = cmd.ExecuteReader(); GridView1.DataSource = rdr; GridView1.DataBind(); } }
And this is my aspx design code:
<%@ Page Title="" Debug="true" Language="C#" MasterPageFile="~/MasterPage2.master" AutoEventWireup="true" CodeFile="TeacherImport.aspx.cs" Inherits="StudentImport" %><asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"><p><br /></p><asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="import" /><br /><br /><asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br /><br /><asp:GridView ID="GridView1" runat="server" Width="1055px"></asp:GridView><br /><br /><br /></asp:Content>
Thank you!