创建直接表示Excel表单的对象列表 [英] Create a list of objects that directly represents an Excel sheet
问题描述
使用LinqToExcel,我试图创建具有动态数量的属性(带值)的对象的动态列表。本质上,对象列表应直接表示Excel表单的内容。但是,我不知道前面的标题名称或数字列。
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.
下面的代码不起作用,甚至没有编译,但是我希望它会显示我想要做的事情。此外,它缺少一种循环方式并添加正确数量的属性。属性的名称和数量应来自列标题数组 columnNameList
。
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();
推荐答案
你想使用LinqToExcel.Row类。以下是共享如何使用文档的文档部分:
You want to use the LinqToExcel.Row class. Here's the section from the documentation that shares how to use it:
查询结果可以返回为LinqToExcel.Row对象,允许您使用字符串索引中的列名访问单元格的值。只需使用 Worksheet()
方法,而不使用通用参数。
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;
LinqToExcel.Row类允许您使用其 Cast<>()
方法
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;
这篇关于创建直接表示Excel表单的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!