c# - 从 Excel 返回数据列表

标签 c# excel linq linq-to-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>();  
    }

这是我的类(class):

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目的。并且您不能将单元格对象分配给整数/字符串/日期时间字段。您只需要使用 Cast<T>方法Cell具有适当的类型参数:

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>()
             };

关于c# - 从 Excel 返回数据列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33163849/

相关文章:

c# - 在将日期时间插入 SQL Server 数据库之前验证日期时间

xml - VBA 使用模式文件提取数据

python - 将 pandas Excel Dataframe 复制到没有索引标题的剪贴板

c# - XML Writer 将结果存储到字符串

c# - LINQ 从 3 个表中选择 Dish/Images/ImageDish

c# - 为列表 c# 中的特定索引应用 lambda 表达式

c# - ASP.Net Azure OpenId 集成

c# - 在 C# 中异步使用 IComparer

c# - 如何在.Net中以中间层结构化方式处理错误或异常

excel - VBA 中的变体数据类型及其积极用途