1

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

4

1 回答 1

1

您可以通过使用 Interop.Excel(Interop C# 教程)或 Interop 的替代品(fe 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

我希望这可以帮到你...

于 2013-05-11T07:59:36.457 回答