在asp.net中将参数传递给excel查询

时间:2012-01-02 16:13:57

标签: c# asp.net excel oledb

我想使用OleDB读取excel文件但是在查询中插入参数时,我有这个OleDb异常:

  

没有给出一个或多个必需参数的值

代码

string conn = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";", opFileImport.FileName);

string sql = "Select CODICE_FISCALE From [Parte_4$] ";
sql += "where CODICE_FISCALE = ?";

using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter())
{
   dataAdapter.SelectCommand = new OleDbCommand(sql, excelConn);
   dataAdapter.SelectCommand.Parameters.Add(new OleDbParameter("Param1", strCodFisc));
   DataTable dt = new DataTable();
   dataAdapter.Fill(dt);
}

1 个答案:

答案 0 :(得分:0)

参数名称应为 CODICE_FISCALE ,而不是 Param1 。试试这段代码

var conn = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";", opFileImport.FileName);
string sql = "Select CODICE_FISCALE From [Parte_4$] ";
sql += "where CODICE_FISCALE = ?";
DataTable dt = new DataTable();
using (OleDbConnection excelConn = new OleDbConnection(conn))
{
    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter())
    {
        dataAdapter.SelectCommand = new OleDbCommand(sql, excelConn);
        dataAdapter.SelectCommand.Parameters.Add(new OleDbParameter("CODICE_FISCALE", strCodFisc));
        dataAdapter.Fill(dt);
    }
}