在使用之前:
1.添加引用
LinqToExcel.dll
Remotion.Data.Linq.dll
2.添加命名空间
using LinqToExcel;
//取得数据,只需要一行代码
var execelfile =
new
ExcelQueryFactory(excelfilename.xls);
|
如何取到相应的表呢?
var tsheet = excelfile.Worksheet(0);
此时得到是没有进行相应映射的(row)行列集合.
一个简单的查询:
1
2
3
4
5
6
7
8
9
10
|
var excelfile =
new
ExcelQueryFactory(
"1.xls"
);
var tsheet = excelfile.Worksheet(0);<br>
//查询30岁以上的人的名字
var query = from p
in
tsheet
where p[
"Age"
].Cast<
int
>() > 30
select p;
foreach
(var item
in
query)
{
Console.WriteLine(
"Name is {0}"
,item[0].Value.ToString());
}
Console.Read();
|
查询结果:
那如何转成相应的实体集合呢?
class
Program
{
static
void
Main(
string
[] args)
{
var excelfile =
new
ExcelQueryFactory(
"1.xls"
);
//用另一种方法取得实体数据集
var tsheet = excelfile.Worksheet<Person>(0);
var query = from p
in
tsheet
where p.Age > 30
select p;
foreach
(var item
in
query)
{
Console.WriteLine(
"Name is {0}"
, item.Name);
}
Console.Read();
}
}
public
class
Person
{
public
string
Name {
get
;
set
; }
public
int
Age {
get
;
set
; }
public
string
Address {
get
;
set
; }
public
Person() { }
public
Person(
string
_name,
int
_age,
string
_address)
{
this
.Name = _name;
this
.Age = _age;
this
.Address = _address;
}
}
|
结果:
这里需要注意的一点:
表头名字如果是英文,(区分大小写)必须与属性名保持一致,要不然会报错的----支持中文属性名和表头
如果将得到的数据集绑定到控件的时候,请最后转List集合:
Winform示例:
后台代码:
前台效果:
总结:感觉这个库文件用起来简单,实用,操作方便,而且结合了Linq的查询特性,excel版本不仅支持03,而且连wps表格都支持(后缀名为.et),csv文件也可以。