从Excel中返回数据列表

我在Excel中有一个数据,我写了一个方法来返回数据,但我不知道如何将它们返回列表中。 这是我的方法:

public List<MyJoin> Excel(string sort, string sortDir, int rowsPerPage, int page, out int count, out string sortCriteria) { count = 0; sortCriteria = ""; var book = new ExcelQueryFactory("/App_Data/Northwind.xsl"); var result = from x in book.Worksheet("Orders") select new { OrderID = x["OrderID"], OrderDate = x["OrderDate"], ShipCountry = x["ShipCountry"], CompanyName = x["CustomerID"], ContactName = x["CustomerID"], EmployeeName = x["EmployeeID"], }; var result2 = result.ToList() ; return result2; //return new List<MyJoin>(); } 

这是我的课程:

 public class MyJoin { public int OrderID { get; set; } public DateTime OrderDate { get; set; } public string ShipCountry { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string EmployeeName { get; set; } } 

result2不能返回LINQ,我不知道如何解决这个问题。

Row[columnName]返回Cell对象。 而且您不能将单元格对象分配给整数/string/date时间字段。 你只需要使用具有适当types参数的Cell Cast<T>方法:

 var result = from r in book.Worksheet("Orders") select new MyJoin { OrderID = r["OrderID"].Cast<int>(), OrderDate = r["OrderDate"].Cast<DateTime>(), ShipCountry = r["ShipCountry"].Cast<string>(), CompanyName = r["CustomerID"].Cast<string>(), ContactName = r["CustomerID"].Cast<string>(), EmployeeName = r["EmployeeID"].Cast<string>() }; 

根据您的评论,您可以直接将列映射到类的属性(前提是它们都具有相同的名称),如下所示: –

  List<MyJoin> result = (from b in book.Worksheet<MyJoin>("Orders") select b).ToList(); 

他们的方式你现在正在做,即如果你没有一个类映射x["OrderID"]是必需的。 x["OrderID"]返回Linq-to-Excel rowobject,您将必须像这样投射: –

 x["OrderID"].Cast<int>