ds ps

ds ps

  • NA
  • 61
  • 0

import data from MS excel to datagridview c#.net 2005

Sep 20 2009 7:49 AM

I have to import data from excel to datagridview control & then to sql database. i tried to import from excel with below code but its showing err msg .. i couldnot understand where it goes wrong... can anyone help me for this.. if its ok or have any other idea to do it.... plz help me at earliest.....

 
Code is like below:
private void btnimport_Click(object sender, EventArgs e)
{
Load_File(dataGridView1,
"C:\\telph.xls", "Sheet1");

}
private void Load_File(DataGridView dg, String filename, String SSheet)
{
string cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;HDR=YES";
try
{
OleDbConnection cn = new OleDbConnection(cs);
if (!System.IO.File.Exists(filename))
{
MessageBox.Show("file not exists");
}
OleDbDataAdapter dAdapter = new OleDbDataAdapter("Select * From [" + SSheet + "$]", cs);
DataSet dts = new DataSet();
dAdapter.Fill(dts);
//DataTable dt = dts.Tables[0];
//return dt;
dg.DataSource = dts.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("ttt");
}
}

Answers (3)