Hello Sir,
How to avoid duplicate rows to be inserted into database while import from excel sheet
I'm trying to import the excel sheet into database.
Below is the code which im using
//Upload and save the file
string excelPath = Server.MapPath("~") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
using (OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["crm_db"].ConnectionString;
SqlConnection con = new SqlConnection(consString);
SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con);
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.crm_tbl_role";
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
ScriptManager.RegisterStartupScript(this, this.GetType(), "SweetAlert", "swal('Success!', 'Data has been been imported successfully to the database', 'success');", true);
con.Close();
}
}
Using the above code if the row is already present into the database then after import the same row is getting insereted .
Table structure is shown below.
CREATE TABLE [dbo].[crm_tbl_role] (
[roleId] INT IDENTITY (1, 1) NOT NULL,
[name] NVARCHAR (50) NULL,
CONSTRAINT [PK_crm_tbl_role] PRIMARY KEY CLUSTERED ([roleId] ASC)
);
Please help
Thanks