如何比较两个Excel工作表并在c#中创建新工作表?

时间:2013-05-11 07:30:03

标签: c# excel

我有两个excel个文件 sheet1有5列值 sheet2只有一列 sheet1和sheet的第一列有一些唯一值。 我需要另一个excelsheet,其中新列有5列(在sheet1和sheet2中匹配唯一值)如何使用C#执行此操作? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以使用Interop.Excel(Interop C# tutorial)或Interop(f.e。ClosedXML)的替代方法来完成此操作。 读入文件并使用LINQ获取所需的数据。使用IEnumerable.Except,您可以从sheet1中获取不在sheet2中的元素,并将其放入新工作表中并将其保存到Excel文件中。

var workbook1 = new XLWorkbook(@"workbook1.xlsx");
var workbook2 = new XLWorkbook(@"workbook2.xlsx");
var worksheet1 = workbook.Worksheet("sheet1");
var worksheet2 = workbook.Worksheet("sheet2");

var listSheet1 = new List<IXLRow>(); // list of Rows
var listSheet2 = new List<IXLRow>();

// puts all UsedRows (including "headers") from sheet1 into a list of rows
using (var rows = worksheet1.RowsUsed())
{
  foreach (var row in rows)
  {
    listSheet1.Add(row);
  }
}

using(var rows = worksheet2.RowsUsed())
{
  foreach (var row in rows)
  {
    listSheet2.Add(row);
  }
}

IEqualityComparer comparer = new XLRowComparer(); // you have to implement your own comparer here. there's a lot of tutorials/samples out there

var uniqueIdList = listSheet1.Intersect(listSheet2, comparer).ToList(); // in this case I'd use intersect instead of except which returns the IDs provided in sheet1 and sheet2

// and now you just have to put the rows from uniqueIdList into a new worksheet and save it

我希望这有用......