如何将日期与行匹配,然后使用EPPlus获得最终列值

本文关键字:EPPlus 然后 日期 | 更新日期: 2023-09-27 18:01:05

到目前为止,我可以从电子表格中简单地获取数据,只需获取参考号行,但我目前不知道如何在获取正确数据之前将行与数据部分匹配。

我目前必须从excel电子表格中提取一些数据,示例如下:

Start date  Ref number
29/07/2015  2342326
01/07/2016  5697455
02/08/2016  3453787
02/08/2016  5345355
02/08/2015  8364456
03/08/2016  1479789
04/07/2015  9334578

主要问题是,是否可以从设置日期、行中读取数据,并从设置日期(如开始日期(中获得参考号。

例如,如果我只是想要从日期设置到上个月1日及以上的数据。

如何最好地实现这一点。

使用基本OleDb:获取列的当前代码示例

using System;
using System.Data.OleDb;
using System.Text.RegularExpressions;
namespace Number_Cleaner
{
    public class NumberCleanerReport
    {
        public void runExcel_Report()
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("[*][START OF: NumberExt.xls, Number Extraction]");
            Console.ResetColor();
            string con =
            @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NumberExt.xls;" +
            @"Extended Properties='Excel 8.0;HDR=Yes;'";
        string connectionString = ExcelWriter.GetConnectionString();
        using (OleDbConnection conn = new OleDbConnection(connectionString))
        {
            conn.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = conn;
            using (OleDbConnection connection = new OleDbConnection(con))
            {
                connection.Open();
                OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection);
                System.IO.StreamWriter files = new System.IO.StreamWriter(Controller.fpath + "NumberExtOutput.txt");
                using (OleDbDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        var row1Col0 = dr[0];
                        string ExcelData = row1Col0.ToString();
                        string subStr = "null";
                        try
                        {
                            subStr = ExcelData.Substring(0, 6);
                        }
                        catch
                        {
                            //Console.WriteLine("Found Nulls.");
                        }
                        if (subStr == "00")
                        {
                            string result = Regex.Replace(ExcelData, "^00", "0");
                            Console.WriteLine(result);
                            files.WriteLine(result);
                            cmd.CommandText = "INSERT INTO [table1]('MainNmbers') VALUES(" + result + ");";
                            cmd.ExecuteNonQuery();
                        }
                    }
                    files.Close();
                    conn.Close();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("[*][END OF: NumberExt.xls, RefNumber Extraction]");
                    Console.ResetColor();
                }
            }
        }
    }
}
}

如何将日期与行匹配,然后使用EPPlus获得最终列值

您可以将其加载到DataTable中,然后用Linq-To-DataTable进行过滤。下面是一个将所有内容都读取为字符串的方法。您可以修改它,使其使用DateTime.ParseDateTime.ParseExactint.Parse:将第一列解析为DateTime,将第二列解析为int

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:

DataTable resultTable = table.Clone();  // empty table with correct columns
if(rowsOfInterest.Count > 0)
    resultTable = rowsOfInterest.CopyToDataTable();