Connect to Excel as data source

Add a button named btnConnect and a datagridview to your project, then add an ODBC dsn Start>Configuration panel>Administration tools> ODBC icon

private void btnConnect_Click(object sender, EventArgs e)

{

OdbcConnection oConn = new OdbcConnection();

//Put your DSN Name that you have already added in the ODBC sources
oConn.ConnectionString = "Dsn=DsnName";

OdbcCommand oComm = new OdbcCommand();

oComm.Connection = oConn;

oComm.CommandText = "Select * From [Feuil1$A1:C3]";

try

{

DataSet ds = new DataSet();

OdbcDataAdapter oAdapter = new OdbcDataAdapter(oComm);

oConn.Open();

oAdapter.Fill(ds);

dataGridView1.DataSource = ds;

dataGridView1.DataMember = ds.Tables[0].TableName;

label1.Text = "Connection established successfully!!!";

}

catch (IOException caught) { MessageBox.Show(caught.Message); }

catch (OdbcException caught) { MessageBox.Show(caught.Message); }

finally

{

oConn.Close();

}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: