我正在做一个将Excel文件导入数据库的程序,该部分工作正常。但是现在,我正在努力避免/防止用户插入或导入重复记录。我试图在所有列中执行复合键,但这没有用。我得到了期望:“ DBNull” ...我认为它通过编码存在另一种方式?
这是我的代码:
protected void Upload_Click(object sender, EventArgs e)
{
string excelPath = Server.MapPath("~/NewFolder/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
string filepath = Server.MapPath("~/NewFolder/") + Path.GetFileName(FileUpload1.FileName);
string filename = Path.GetFileName(filepath);
FileUpload1.SaveAs(excelPath);
string ext = Path.GetExtension(filename);
String strConnection = @"Data Source=Ricky-PC\SQLEXPRESS;Initial Catalog=ImportHere;Persist Security Info=True;User ID=sa;Password=******";
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HDR=NO;IMEX=1;\"";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable schema = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = schema.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("Select * from ["+sheetName+"]", excelConnection);
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
sqlBulk.DestinationTableName = "Data";
sqlBulk.ColumnMappings.Add(0,0);
sqlBulk.ColumnMappings.Add(1,1);
sqlBulk.ColumnMappings.Add(2,2);
sqlBulk.ColumnMappings.Add(3,3);
sqlBulk.WriteToServer(dReader);
}
excelConnection.Close();
}
答案 0 :(得分:0)
尝试加载临时表,然后使用存储的proc合并到最终表。合并将允许您更新现有记录并插入新记录。这不会插入重复项。如果不需要更新,那么从暂存到最终表的插入也将起作用,因为您可以过滤出匹配的记录,而仅插入与现有记录不匹配的记录。