Import Data From Excel

Posted by Tamilmaran under C# category on | Views : 2174
Dear All

he below code is used to import data from the excel file. here i use openfiledialog to get excel file name. Connection string connects to the specified excel file. dataGridView1.DataSource = objDataset1.Tables[0];
statements binds the datagrid with objDataset values.

OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select Excel file only";
ofd.CheckFileExists = false;
ofd.CheckPathExists = true;
ofd.AddExtension = true;
ofd.DefaultExt = "txt";
ofd.ShowReadOnly = true;
ofd.ShowHelp = true;
if (ofd.ShowDialog() == DialogResult.Cancel)
strfile = ofd.FileName.ToString();
DataSet objDataset1 = new DataSet();
string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+strfile +";Extended Properties=Excel 5.0";
OleDbConnection objConn = new OleDbConnection(ConnectionString);
String strConString = "SELECT * from [Sheet1$]";
OleDbCommand objCmdSelect = new OleDbCommand(strConString, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataTable dt = new DataTable();
objAdapter1.Fill(objDataset1, "ExcelData");
dataGridView1.DataSource = objDataset1.Tables[0];

Comments or Responses

Login to post response