I have an excel file that i need to open and search it. This is the code i use:
public partial class _Default : System.Web.UI.Page
{
string connStr;
string absoluteDir;
string relativeDir;
protected void Page_Load(object sender, EventArgs e)
{
relativeDir = "~/data" + System.IO.Path.DirectorySeparatorChar + "zadacaEXCEL.xlsx";
absoluteDir = Server.MapPath( relativeDir );
Label1.Text = absoluteDir + " ";
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + absoluteDir + ";Extended Properties=\"Excel 8.0;HDR=Yes\"";
//string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
// Create the connection object
OleDbConnection oledbConn = new OleDbConnection(connStr);
try
{
// Open connection
oledbConn.Open();
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds);
// Bind the data to the GridView
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch(Exception err)
{
Label1.Text += err.ToString();
}
finally
{
// Close connection
oledbConn.Close();
}
}
and this is the error i get:
System.Data.OleDb.OleDbException: External table is not in the expected format. at
System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at
System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at
System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at
System.Data.OleDb.OleDbConnection.Open() at
_Default.Page_Load(Object sender, EventArgs e) in c:\Users\ACO\Documents\Visual Studio 2008\WebSites\za_rabota\Default.aspx.cs:line 33
The error occurs at oledbConn.Open();
Can someone PLEASE tell me what am i doing wrong here. the excel file is in folder named data in the solution