在特定条件下更新数据网格视图中的 Excel 值



我需要从 winform 的数据网格视图中的 excel 表中获取行值。

我能够在数据网格视图中显示整个 excel 工作表。但是,我需要根据当前日期条件在网格中显示特定行。

public DataTable ReadExcel2(string fileName, string fileExt)
{
string connectionstring ;
DataTable dtexcel2 = new DataTable();
connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand oconn = new OleDbCommand("Select * From [POSFailures$]  WHERE Date=@date");
oconn.Connection = connection;
try
{
oconn.Parameters.AddWithValue("@date", DateTime.Now.ToString("MM/dd/yyyy"));
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}
return dtexcel2;
}

提前感谢你

这里似乎发生的事情是 Date 参数没有得到遵守,因为您正在返回所有行。 因此,我使用Google来弄清楚如何在使用OleDbConnection时正确添加参数。我发现这个:

OLE DB .NET 提供程序不支持将参数传递给 SQL 语句的命名参数

来源:https://learn.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.parameters?redirectedfrom=MSDN&view=netframework-4.8#System_Data_OleDb_OleDbCommand_Parameters

使用该页面上的示例,尝试将代码更改为以下内容:

string connectionstring;
DataTable dtexcel2 = new DataTable();
connectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=YES';";
OleDbConnection connection = new OleDbConnection(connectionstring);
OleDbCommand command = new OleDbCommand("Select * From [POSFailures$]  WHERE Date = ?");
command.Parameters.Add(new OleDbParameter(DateTime.Now.ToString("MM/dd/yyyy"), OleDbType.Date));
command.Connection = connection;
try
{
connection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
sda.Fill(dtexcel2);
connection.Close();
}
catch (Exception)
{
}

请注意,我还没有测试过这个,所以我不能保证它会起作用。但是,重点是...答案就在那里! 你只需要去寻找它。

最新更新