您可以将其加载到
DataTable
然后用过滤
Linq-To-DataTable
.
Here's a method
读取所有字符串的。您可以修改它,以便它将第一列解析为
DateTime
第二个到
int
具有
DateTime.Parse
或
DateTime.ParseExact
和
int.Parse
:
public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return tbl;
}
}
一旦表中有了正确的类型,查询就很简单:
var rowsOfInterest = table.AsEnumerable()
.Where(row => row.Field<DateTime>("Start date") >= new DateTime(2016, 7, 1))
.ToList();
数据表
:
DataTable resultTable = table.Clone(); // empty table with correct columns
if(rowsOfInterest.Count > 0)
resultTable = rowsOfInterest.CopyToDataTable();