我正在插入数据库excel工作表,我已经可以使用工作表名和不使用工作表名上传,我只想知道如何防止数据多次插入,例如如果我的工作表有2条记录,则循环将其插入两次,并且表最终看起来像这样:
ID DOB NAME SURNAME
1 1/02/1998 jack turner
2 2/02/1989 jill blue
1 1/02/1998 jack turner
2 2/02/1989 jill blue
代码:
public void up(string sFileName = @"filename") {
string ssqltable = "[dbo].[My_Table]";
//string sFileName = @"filename";
try{
string sConStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES';", sFileName);
DataTable dt = new DataTable();
SqlConnection sqlconn = new SqlConnection(strConnString);
sqlconn.Open();
using (OleDbConnection connection = new OleDbConnection(sConStr))
{
connection.Open();
dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
var sheets = dt.Rows[0].Field<string>("TABLE_NAME");
foreach(var sheet in sheets) //loop through the collection of sheets ;)
{
//your logic here...
string myexceldataquery = string.Format("Select * FROM [{0}]; ", sheets);
//get data
OleDbConnection oledbconn = new OleDbConnection(sConStr);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
{
DataTable table = new DataTable("benlist");
table.Load(dr);
// add two extra columns to data table to be added to database table
table.Columns.Add("name",typeof(string));
table.Columns.Add("surname",typeof(string));
// add data to additional columns
foreach (DataRow row in table.Rows){
row["name"] =Session["Username"].ToString();
row["surname"] = Session["Username"].ToString();
}
SqlBulkCopy bulkcopy = new SqlBulkCopy(strConnString);
bulkcopy.DestinationTableName = ssqltable;
////Mapping Table column
bulkcopy.ColumnMappings.Add("IDNumber", "[IDNumber]");
bulkcopy.ColumnMappings.Add("DOB", "[DOB]");
bulkcopy.ColumnMappings.Add("name", "[name]");
bulkcopy.ColumnMappings.Add("surname", "[surname]");
//sqlcmd.ExecuteNonQuery();
//while (dr.Read())
//{
bulkcopy.WriteToServer(table);
//}
connection.Close();
sqlconn.Close();
}
}
}
}
catch (Exception){}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('File Uploaded');", true);
}
我希望一旦没有重复就插入数据
ID DOB NAME SURNAME
1 1/02/1998 jack turner
2 2/02/1989 jill blue
答案 0 :(得分:0)
所以我删除了循环,将数据插入数据库表后不再重复数据了,谢谢
参考:Getting the first sheet from an Excel document regardless of sheet name with OleDb
using (OleDbConnection connection = new OleDbConnection(sConStr))
{
connection.Open();
/// get sheet name
dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//var sheets = dt.Rows[0].Field<string>("TABLE_NAME");
// foreach(var sheet in sheets) //loop through the collection of sheets ;)
// {
var sheets = dt.Rows[0].Field<string>("TABLE_NAME");
//your logic here...
string myexceldataquery = string.Format("Select * FROM [{0}]; ", sheets);
//get data