void copy_excel_sheet_to_datagridview ( )
{
string sheet_name = "Sheet1";
if ( !retrieved_excel_filename ( ) )
{
return;
}
if ( !sheet_name_valid ( sheet_name ) )
{
return;
}
try
{
OleDbConnection connection = null;
StringBuilder connection_string =
new StringBuilder ( );
DataSet data_set = new DataSet ( );
string select_command = String.Empty;
connection_string.AppendFormat (
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source='{0}';" +
"Extended Properties=Excel 8.0;",
excel_filename );
select_command = String.Format (
"select * from [{0}$]",
sheet_name );
try
{
connection = new OleDbConnection (
connection_string.
ToString ( ) );
}
catch ( Exception ex )
{
MessageBox.Show ( String.Format (
"{0}{1}{2}",
ex.Message,
Environment.NewLine,
ex.StackTrace ),
"Failed to create connection" );
return;
}
try
{
OleDbDataAdapter adapter = null;
OleDbCommand command = null;
command = new OleDbCommand ( select_command,
connection );
adapter = new OleDbDataAdapter ( command );
connection.Open ( );
adapter.Fill ( data_set );
}
catch ( Exception ex )
{
MessageBox.Show ( String.Format (
"{0}{1}{2}",
ex.Message,
Environment.NewLine,
ex.StackTrace ),
"Failed to retrieve data" );
return;
}
finally
{
connection.Close();
}
dataGridView1.DataSource = null;
dataGridView1.DataSource = data_set.Tables [ 0 ];
}
catch ( Exception ex )
{
MessageBox.Show ( String.Format (
"{0}{1}{2}",
ex.Message,
Environment.NewLine,
ex.StackTrace ),
"Failed setup" );
return;
}
}