Wednesday, December 3, 2008

import from excel in c#

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
path = openFileDialog1.FileName;
}

private void btnImport_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "excel file |*.xls";
openFileDialog1.FilterIndex = 1;
openFileDialog1.InitialDirectory = "%My Documents%";
openFileDialog1.ShowDialog(this);
// path = openFileDialog1.FileName;
if (path != "")
{
try
{
oledbConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + @"; Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""";
olebdConn.ConnectionString = oledbConnectionString;
oledbCmmd.Connection = olebdConn;
oledbCmmd.CommandText = "Select * FROM [Sheet1$]";
olebdConn.Open();
da =new OleDbDataAdapter(oledbCmmd);
da.Fill(ds);

dgvExcelData.Visible = true;
////dt = dr.GetData(4);
int count = ds.Tables[0].Rows.Count;
label2.Text = count.ToString();
////dgvExcelData.Rows.Clear();

dgvExcelData.DataSource = ds.Tables[0];
////dgvExcelData.Visible = true;
olebdConn.Close();
}

1 comment:

Anonymous said...

thanks amigo! great post!.