访问Excel数据表时出错

时间:2016-07-21 09:18:31

标签: c# excel

我必须从excel工作表访问数据,但是在将数据(从excel)复制到数据集时遇到问题

try
{
    string strPath = FileName;
    DataSet ds = new DataSet();
    string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; " + "Data Source=" + strPath + "; " + "Extended Properties=Excel 8.0;";

    OleDbConnection objConn = new OleDbConnection(sConnectionString);
    objConn.Open();
    OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + TableName + "] ", objConn);
    OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
    objAdapter1.SelectCommand = objCmdSelect;
    objAdapter1.Fill(ds);
    objAdapter1.Dispose();//DEBUGGER SKIP FROM HERE
    objConn.Close();
    return ds.Tables[0];
}
catch (Exception ex)
{
    //Log your exception here.//
    return (DataTable)null;//AND THEN JUMP TO HERE
}

问题是,在调试时,在行objAdapter1.Fill(ds);调试器之后跳过剩余的行,当然数据集返回null,请帮忙。

1 个答案:

答案 0 :(得分:0)

您的连接字符串中的扩展属性必须是双引号。请尝试以下行:

string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; " +
                           "Data Source=" + strPath + "; " + 
                           "Extended Properties=\"Excel 8.0;\"";