Create a list of objects that directly represents an Excel sheet

余生颓废 提交于 2019-12-11 09:07:58

问题


Using LinqToExcel, I'm trying to create a dynamic list of objects that have a dynamic number of properties (with values). Essentially, the list of objects should directly represent the contents of an Excel sheet. However, I don't know the header names or the number columns before hand.

The code below does not work, it doesn't even compile, but I'm hoping it will show what I'm trying to do. Also it is missing a way to loop and add the correct number of properties. The names and number of properties should come from an array of column headers columnNameList .

    // get the records
    var excel = new ExcelQueryFactory(path);
    IEnumerable<string> columnNameList = excel.GetColumnNames(mod.SelectedSheet);
    var ExpandoObject = (from x in excel.Worksheet(selectedSheet)
                          select new ExpandoObject()
                          {
                              ExpandoObject.Prop1 = x["excelCol1"],
                              ExpandoObject.Prop2 = x["excelCol2"],
                              ExpandoObject.Prop3 = x["excelCol3"],
                              ExpandoObject.Prop4 = x["excelCol4"],
                              ExpandoObject.Prop5 = DateTime.Now
                          }).ToList(); 

回答1:


You want to use the LinqToExcel.Row class. Here's the section from the documentation that shares how to use it:

Using the LinqToExcel.Row class

Query results can be returned as LinqToExcel.Row objects which allows you to access a cell's value by using the column name in the string index. Just use the Worksheet() method without a generic argument.

var excel = new ExcelQueryFactory("excelFileName");
var indianaCompanies = from c in excel.Worksheet()
                       where c["State"] == "IN" || c["Zip"] == "46550"
                       select c;

The LinqToExcel.Row class allows you to easily cast a cell's value by using its Cast<>() method

var excel = new ExcelQueryFactory("excelFileName");
var largeCompanies = from c in excel.Worksheet()
                     where c["EmployeeCount"].Cast<int>() > 500
                     select c;


来源:https://stackoverflow.com/questions/29482949/create-a-list-of-objects-that-directly-represents-an-excel-sheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!