上传并更新Excel文件

时间:2018-09-21 10:55:01

标签: asp.net sql-server sql-server-2008

我有一个任务来上传excel文件,并检查更新是否找到相同的记录,我已经将excel文件上传到了可以正常工作的数据库中。

现在,我必须检查是否插入了相同的记录,然后进行更新,否则要插入新记录,我首先有两个表,将记录插入到临时表中,然后再检查原始表中的临时表,如果记录匹配,然后更新,否则插入,我使用嵌套的for循环来检查记录 我的循环工作正常并插入了前两个记录,但是当涉及到第三个记录时,将其插入多次,然后在第四次插入多次,请指导我做错了什么 到目前为止,这是我的代码

oldest=timestamp

1 个答案:

答案 0 :(得分:0)

如果仅使用临时表来检查原始表中是否存在该行,那么这不是一个好习惯。

使用主键id或任何Unique Key直接检查原始表中是否存在该行,然后决定是Insert还是Update

一种方法,

while (dr.Read()) 
{
    if (dr[0].ToString() != "") 
    {
       id = Convert.ToInt32(dr[0].ToString());        //add other columns which needs to be fetched from Excel
       string query = "select count(1) from Tbl_ExcelData where id=?";        //To check if the row already exsits    
       SqlCommand cmd = new SqlCommand(con);

       cmd.CommandText = query;
       cmd.Paramaters.Add(new SqlParameter(1, id));

       int count = (Int32) cmd.ExecuteScalar();

       if (count > 0) //which means row already exists
       {
          //Your update code goes here
       } 
       else 
       {
            InsertOrignal(id, contactPerson, designation, company, emailaddress, contact, mobile, address, city, region, industry, division);
       }
}

评论后,这是一个基本概念。将Excel数据加载到DataTable并循环遍历并确定Upsert的一种方法。记住要了解MultipleActiveResultSets

try
{
    string ExcelPath = Server.MapPath("~/uploadExcel/") + FileUpload1.FileName;
    string _oleDBConnectionString = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 8.0; Persist Security Info = False", ExcelPath);
    string _sqlConnectionString = "Data Source=Ali-PC;Initial Catalog=MushkhoApp;Integrated Security=True; MultipleActiveResultSets=true;"; //enable MultipleActiveResultSets as you'll be opening a nested SqlConnection
    string _excelQuery = "select * from [Sheet1$]";
    DataTable tempDataTable = null;

    using (var conn = new OleDbConnection(_oleDBConnectionString)) //This code loads your excel data into data table
    {
        conn.Open();
        using (var cmd = new OleDbCommand(_excelQuery, conn))
        {
            using (var reader = cmd.ExecuteReader())
            {
               var dt = new DataTable();

               dt.Load(reader); //this will load your excel data into DataTable

               tempDataTable = dt;
            }
        }
    }

    using(var sqlConn = new SqlConnection(_sqlConnectionString)) //this code will connect to sql db and upsert based on the id from the excel
    {
        sqlConn.Open();

        string countQuery = "select count(1) from Tbl_ExcelData where id=:id";    

        using(var cmd = new SqlCommand(countQuery, sqlConn))
        {
            var param = new SqlParameter("@id");

            foreach (DataRow row in tempDataTable.Rows) //this will loop through the DataTable rows, the actual rows from Excel which are loaded into DataTable
            {
                var id = row["id"]; //get the id column from the excel
                var contactPerson = row["contactPerson"]; //get the contactPerson column from the excel

                cmd.Paramaters["@id"] =  id;

                int count = (int) cmd.ExecuteScalar();

                if (count) //row already exist in original table
                {
                    //update the row in original table
                }
                else
                {
                    //insert the row in original table
                    InsertOriginal(sqlConn, id, contactPerson);
                }
            }               
        }
     }
 }
 catch(Exception ex)
 {
 }

function InsertOriginal(SqlConnection conn, int id, string contactPerson)
{
    string insertQuery = "insert into Tbl_ExcelUploadData (id,contactpersonn) values('@id','@contactPerson');

    using(var cmd = new SqlCommand(insertQuery, conn))
     {
         cmd.Parameters.Add(new SqlParameter("@id",id));
         cmd.Parameters.Add(new SqlParameter("@contactPerson", contactPerson));
         cmd.ExecuteNonQuery();
     }
}

此外,这不是经过测试的代码。随时发表评论。