【问题标题】:Import excel file to sql server in asp.net with check existing record in table before import将excel文件导入asp.net中的sql server,并在导入前检查表中的现有记录
【发布时间】:2012-03-19 14:16:57
【问题描述】:

对不起,我的英语不好!

如何检查excel文件,如果表中存在的行不导入该行

我的功能适用于导入(不检查现有)

string excelConnectionString = "";
    string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
    string strFileType = System.IO.Path.GetExtension(fileuploadExcel.FileName).ToString().ToLower();
    fileuploadExcel.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
    string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
    //Connection String to Excel Workbook
    if (strFileType.Trim() == ".xls")
    {
        excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;Persist Security Info=False";
    }
    else if (strFileType.Trim() == ".xlsx")
    {
        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
    }

  //Create Connection to Excel work book
    OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);
    //Create OleDbCommand to fetch data from Excel
    OleDbCommand cmd = new OleDbCommand("Select [account_id], [type],[first_name], [last_name], [title], [birthday], [tel],[phone], [email_1],[email_2], [remark],[del_if] from [Sheet1$]",excelConnection);
    excelConnection.Open();
    OleDbDataReader dReader;
    dReader = cmd.ExecuteReader();
    SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
    //Give your Destination table name
    sqlBulk.DestinationTableName = "contact";

    sqlBulk.WriteToServer(dReader);

【问题讨论】:

    标签: asp.net sql-server import


    【解决方案1】:

    我不知道这是否可以使用 SqlBulkCopy。您可以做的是将数据写入临时表,并且只复制不存在的记录。然后,您可以在副本完成后清除暂存表。

    编辑:

    鉴于您对不想使用临时表的评论,您可能会在从 excel 文件中读取数据之前从“联系人”表中找到不同的键值列表(可能是您的示例中的 account_id),然后使用列表以排除您从 excel 文件中读取的记录。这样做的好处是您不会从不需要的 excel 文件中读取数据。不利的一面是,如果您的“联系人”表很大,或者您用于比较数据的键不是 account_id 之类的简单内容,这可能不会那么有效。

    如果您的 excel 文件不大,另一种选择可能是在插入时使用 where 子句逐行插入记录,以确保插入不会产生不必要的重复。这将比 SqlBulkCopy 慢得多,但它会起作用。

    【讨论】:

    • 如果不能使用SqlBulkCopy,我可以使用其他方式。我只想解决“导入前检查”。写入临时表,然后将不存在的记录复制到其他表可能更复杂
    • @Hainlp- 在我编辑的帖子中列出了几个替代方案。我希望它们有一些用处。祝你好运。主要问题是 SqlBulkCopy 对选择性插入没有用。它只是尽可能快地填充数据。问题的症结在于要么先过滤需要填入数据库的数据,要么不使用SqlBulkCopy。
    • @穆斯先生:谢谢。我想我需要阅读有关存储过程的更多信息并找到其他导入方式(不要使用 SqlBulkCopy)。再次感谢穆斯先生 :)。
    猜你喜欢
    • 2016-03-08
    • 2014-04-05
    • 2014-11-06
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多