Take one TextBox In the property (Name)=txtPath
OpenFileDialog Property (Name)=ofd
one Button Property (Name)=btnBrows
two RadioButton 1st Property (Name)= rdbY 2nd Property (Name)=rdbN
one DtaGridView Property (Name)=dataGridView1
Now see the code --.cs
private void btnBrows_Click(object sender, EventArgs e)
{
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.OK)
{
string file = ofd.SafeFileName;
string Extension = Path.GetExtension(ofd.FileName);
Import_To_Grid(ofd.FileName, Extension, isRDB);
}
}
private void Import_To_Grid(string FilePath, string Extension, string isHDR)
{
string conStr = "";
switch (Extension)
{
case ".xls":
conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
conStr = String.Format(conStr, FilePath, isHDR);
OleDbConnection connExcel = new OleDbConnection(conStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
oda.Fill(dt);
connExcel.Close();
dataGridView1.DataSource = dt;
}
string isRDB = string.Empty;
private void rdbY_CheckedChanged(object sender, EventArgs e)
{
isRDB = "Yes";
}
private void rdbN_CheckedChanged(object sender, EventArgs e)
{
isRDB = "No";
}
App.Config settings
<connectionstrings>
<add name="Excel03ConString" connectionstring="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}; Extended Properties='Excel 8.0;HDR={1}'" />
<add name="Excel07ConString" connectionstring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0;HDR={1}'" />
</connectionstrings>