使用C#在2个日期之间查询Excel列

时间:2012-11-20 21:39:57

标签: c# sql excel oledb

您好我试图从两个日期之间的Excel中选择一个数据。我有点卡住,因为excel中的数据只是文本类型。我该如何查询?

string Date = DateTime.Now.AddDays(7).ToString("dd/MM/yyyy HH:mm");

string Date2 = DateTime.Now.ToString("dd/MM/yyyy HH:mm");

MyCommand = new System.Data.OleDb.OleDbDataAdapter("select [Req Start Date] from [CR$]", BETWEEN Date and Date2 ? MyConnection);

1 个答案:

答案 0 :(得分:1)

您可以使用标准SQL语法在两个日期之间进行查询,但需要将日期作为日期参数分配给OleDbDataAdapter。否则,它会将日期视为文本,您将无法获得正确的匹配。

DataSet ds = new DataSet();

using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(SQL, conn))
{
    // Format the dates as dd/mm/yyyy

    string date1 = DateTime.Now.AddDays(7).ToString("dd/MM/yyyy");
    string date2 = DateTime.Now.ToString("dd/MM/yyyy");

    // Set up the SQL with the two date paramters

    string SQL = "SELECT [Req Start Date] FROM [CR$] WHERE [Req Start Date] BETWEEN ? AND ?";

    // Assign the two dates

    dataAdapter.SelectCommand.Parameters.Add("@p1", OleDbType.Date).Value = date1;
    dataAdapter.SelectCommand.Parameters.Add("@p2", OleDbType.Date).Value = date2;

    // Run the query

    dataAdapter.Fill(ds);
}