问题
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