在将数据存储到SQL Server表时,如何从多个Excel工作表中阻止重复值

时间:2016-11-30 04:58:25

标签: c# sql-server excel sqlbulkcopy database-table

private void InsertExcelRecords(string filepath)
{
    ExcelConn(filepath);            
    OleDbCommand Ecom = new OleDbCommand(Query, Econ);  
    Econ.Open();
    DataTable dtSheet = Econ.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

    foreach (DataRow dr in dtSheet.Rows)
    {
       string sheetName = dr["TABLE_NAME"].ToString();

       if (!sheetName.EndsWith("$"))
           continue;

       Query = string.Format("select * from  [" + sheetName + "]");       

       DataSet ds=new DataSet();  
       OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);  
       Econ.Close();  
       oda.Fill(ds);  
       DataTable Exceldt = ds.Tables[0];

       using (SqlConnection con = new SqlConnection(strConnString))
       {
           //connection();  
           //creating object of SqlBulkCopy    
           SqlBulkCopy objbulk = new SqlBulkCopy(con);  

           //assigning Destination table name    
           objbulk.DestinationTableName = "tblCompany"; 

           //Mapping Table column        
           objbulk.ColumnMappings.Add("Company", "CompanyName");
           objbulk.ColumnMappings.Add("Contact Telephone", "CompanyContactNumber");
           objbulk.ColumnMappings.Add("Website", "Website");
           objbulk.ColumnMappings.Add("Location", "Location");
           objbulk.ColumnMappings.Add("Targetted for", "TargettedFor");

           con.Open();  
           objbulk.WriteToServer(Exceldt);
           con.Close();
       }
    }
}

如何在导入SQL Server表时防止Excel工作表中的重复数据?

0 个答案:

没有答案