0

i am trying to create a webpage which has option to browse an excel file and upload it to the database. but if i make some changes to the same excel and then upload it again. it should update the existing data in the database. but what actually happens that it gets re inserted.

this is my code

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string con_str = "Data Source=BG1WS0154\\SQLEXPRESS;Initial Catalog=studentdetails;Integrated Security=True";
            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();



            // Bulk Copy to SQL Server 
            SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
            bulkInsert.DestinationTableName = "tbl_studentdetails";
            bulkInsert.WriteToServer(dr);
            OleDbcon.Close();
            Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
            Label1.ForeColor = Color.Green;
            Label1.Text = "successfully inserted";


        }
        else
        {
            Label1.ForeColor = Color.Red;
            Label1.Text = "Please select the File";
        }
    }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364

1 Answers1

0

That's not going to happen with SqlBulkCopy. That's meant for just copying all the data into a table and not for logic like you are needing. Use a temp table as described in this thread: C# Bulk Insert SQLBulkCopy - Update if Exists

Community
  • 1
  • 1
Mark Fitzpatrick
  • 1,624
  • 1
  • 11
  • 8