如何使用oledb删除excel表单中的重复记录

问题描述:

我有一个Excel表单,包含4列(JobCode,JobName,StartDate,EndDate)。在一个规则的基础上,我必须验证第1张excel表格,并将第2张excel表格中的所有记录(第1张excel表格中存在的重复记录除外)全部插入。 我试图使用列表。但它按预期工作。如何使用oledb删除excel表单中的重复记录

List<string> JobCodeList = new List<string>(); 
for (int iRowCount = 0; iRowCount < hrms_jobdata.Tables[0].Rows.Count; iRowCount++) 
{ 
    JobCode = hrms_jobdata.Tables[0].Rows[iRowCount]["Job Code"].ToString(); 
    JobName = hrms_jobdata.Tables[0].Rows[iRowCount]["Job Name"].ToString(); 
    StartDate = hrms_jobdata.Tables[0].Rows[iRowCount]["Start Date"].ToString(); 
    EndDate = hrms_jobdata.Tables[0].Rows[iRowCount]["End Date"].ToString(); 
    JobCodeList.Add(JobCode + JobName); 
} 

connectionhrms_job.Close(); 


for (int iRowCount = 0; iRowCount < hrms_jobdata.Tables[0].Rows.Count; iRowCount++) 
{ 
    JobCode = hrms_jobdata.Tables[0].Rows[iRowCount]["Job Code"].ToString(); 
    JobName = hrms_jobdata.Tables[0].Rows[iRowCount]["Job Name"].ToString(); 
    StartDate = hrms_jobdata.Tables[0].Rows[iRowCount]["Start Date"].ToString(); 
    EndDate = hrms_jobdata.Tables[0].Rows[iRowCount]["End Date"].ToString(); 

    DateTime convertedstart = DateTime.Parse(StartDate); 
    StartDateFormated = convertedstart.ToString("dd-MM-yyyy"); 

    DateTime convertedend = DateTime.Parse(EndDate); 
    EndDateFormated = convertedend.ToString("dd-MM-yyyy"); 

    List<string> dupvalue = removeDuplicates(JobCodeList); 

    foreach (string value in dupvalue) 
    { 
     string jobcodename = value; 
    } 

    string connectionStringdest = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathdestination + ";Extended Properties=Excel 12.0;"; 
    DbProviderFactory factorydest = DbProviderFactories.GetFactory("System.Data.OleDb"); 
    DbConnection connectiondest = factorydest.CreateConnection(); 
    connectiondest.ConnectionString = connectionStringdest; 
    DbCommand command = connectiondest.CreateCommand(); 
    StringBuilder inserthrms_job = new StringBuilder(); 
    inserthrms_job = inserthrms_job.Append("Insert into [hrms_job$] values ('" + JobCode + "', '" + JobName + "', '" + StartDateFormated + "', '" + EndDateFormated + "','" + JobCode + " " + JobName + "') "); 
    inserthrms_job = inserthrms_job.Append(";"); 
    command.CommandText = inserthrms_job.ToString(); 
    connectiondest.Open(); 
    command.ExecuteNonQuery(); 
    connectiondest.Close(); 
} 
+0

嗯,你的代码格式的一部分出了问题,我没有看到你的问题是什么。你说你想要它做什么,然后你说列表正在按预期工作......但不是你遇到什么麻烦。 – 2011-01-11 17:51:03

当你查询源电子表格,只需做一个“由字段1,字段2,字段3选择顶层1字段1,字段2,从[表$]组字段3”。这样你只能读取第一条记录,而不是重复记录。

好问题 - 我不认为通过oledbadapter中的SELECT语句,我可以看到每个答案(如果有的话,请指教)。

看到这个OleDBAdapter Excel QA我通过堆栈溢出发布。

把你的数据集放入一个对象,就像我在帖子底部所做的一样。

然后通过enumerable.distinct(see MSDN example)扩展对象,因此您的对象通过使用默认的相等比较器来比较值,从而从一个序列中返回不同的元素。

然后在该帖子底部:

var noduplicates = query.Distinct(); 
foreach (var rec in noduplicates) 
    Console.WriteLine(rec.ManagedLocationID + " " + rec.PartID + " " + rec.Quantity);