private void button2_Click(object sender, EventArgs e) { try { OpenFileDialog openfiledialog1 = new OpenFileDialog(); openfiledialog1.ShowDialog(); string filePath = openfiledialog1.FileName; string extension = Path.GetExtension(filePath); string header = rdbuttonyes.Checked ? "YES" : "NO"; string conStr, sheetName; conStr = string.Empty; switch (extension) { case ".xls": //Excel 97-03 conStr = string.Format(Excel03ConString, filePath, header); break; case ".xlsx": //Excel 07 conStr = string.Format(Excel07ConString, filePath, header); break; } //Get the name of the First Sheet. using (OleDbConnection con = new OleDbConnection(conStr)) { using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = con; con.Open(); DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString(); con.Close(); } } //Read Data from the First Sheet. using (OleDbConnection con = new OleDbConnection(conStr)) { using (OleDbCommand cmd = new OleDbCommand()) { using (OleDbDataAdapter oda = new OleDbDataAdapter()) { DataTable dt = new DataTable(); cmd.CommandText = "SELECT * From [" + sheetName + "]"; cmd.Connection = con; con.Open(); oda.SelectCommand = cmd; oda.Fill(dt); //dgvExcelResult.SelectedRows.ToString(); con.Close(); //dgvExcelResult.AutoGenerateColumns = false; //Populate DataGridView. dgvExcelResult.DataSource = dt; dgvExcelResult.Visible = true; } } } } catch(Exception) { } }
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.CommandText = "SELECT Name, Age, Gender From [" + sheetName + "]";
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)