LinqToExcel:excel列中的不同值 [英] LinqToExcel: Distinct values in excel column
问题描述
这可能是一个非常简单的事情,你的大师,但我不熟悉C#4和INTEROP。所以,我被骗了。这里是我的问题。
我有一个excel列有重复的数据,我想修剪它只有唯一的值。以下是数据的样子:
This might be a very simple thing for you gurus, but I'm not familiar with C#4 and INTEROP. Therefore, I'm stumped. Here's my problem. I have a excel column that has duplicate data and I want to trim it down to only unique values. Here's what the data looks like:
ColA ColB
10 Adam
12 Jane
14 Adam
18 Adam
20 Eve
来自ColB的唯一名称:
So, in the end I just want unique names from ColB:
Adam
Jane
Eve
我知道我可以通过将所有这些值放入列表然后添加Distinct功能来实现。但我想我做错了。无论如何,这里是我的程序:
I know that I can do this by getting all those values into a List and then adding the Distinct functionality to it. But I think I'm doing something wrong. Anyway, here's my program:
Application XLApp = new Microsoft.Office.Interop.Excel.Application();
var XLBook = XLApp.Workbooks.Open(@"c:\temp\Test.xls", ReadOnly: false);
// Grab the 1st sheet
var XLSheet = (Microsoft.Office.Interop.Excel.Worksheet)XLBook.Worksheets.get_Item(1);
XLApp.Visible = true;
// I think I need help with the following lines
IEnumerable<string> myCol = XLApp.Range["B2", XLApp.Range["B2"].End[XlDirection.xlDown]].Select();
myCol.ToList().Distinct();
XLBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
((_Application)XLApp).Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(XLApp);
如何使用C#4来处理Excel?
How do I go about doing this using C#4 against Excel?
提前感谢。
推荐答案
您可以使用 LinqToExcel 轻松获取列中的不同值
You can use LinqToExcel to easily get the distinct values in a column
var excel = new ExcelQueryFactory("worksheetFileName");
var distinctNames = (from row in excel.WorkSheet()
select row["ColB"]).Distinct()
编辑:
要在LinqToExcel中使用 Distinct
使用与行数据对应的类。
To use Distinct
in LinqToExcel, you have to use a class that corresponds to the row data.
public class WorksheetRow
{
public string ColA { get; set; }
public string ColB { get; set; }
}
var excel = new ExcelQueryFactory("worksheetFileName");
var distinctNames = (from row in excel.WorkSheet<WorksheetRow>()
select row.ColB).Distinct()
这篇关于LinqToExcel:excel列中的不同值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!