In fact, there is no difference between displaying the data in the Excel table in the datagridview datagriand reading the data in the database, except that the connection fields are slightly different when you create a database connection.
Private void btnshow_click (Object sender, eventargs E)
{
Openfiledialog ofd = new openfiledialog ();// Select an Excel table based on the open file dialog box.
Ofd. Filter = "Table | *. xls ";// Open File Dialog Box Filter
String strpath ;// Complete file path name
If (OFD. showdialog () = dialogresult. OK)
{
Try
{
Strpath = ofd. filename;
String strcon = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + strpath + "; Extended properties = Excel 8.0 ";// The key is the red area.
Oledbconnection con = new oledbconnection (strcon );// Establish a connection
String strsql = "select * from [Sheet1 $] ";// Note that the table names are written differently. The corresponding Excel table is sheet1. Here, you need to add the dollar sign $ and enclose it in brackets.
Oledbcommand cmd = new oledbcommand (strsql, con );// Create the command to be executed
Oledbdataadapter da = new oledbdataadapter (CMD );// Create a data adapter
Dataset DS = new dataset ();// Create a dataset
Da. Fill (DS, "shyman ");// Read the data in the data adapter to a table in the dataset (the table name here is shyman. You can use any table name)
// Specify the data source of datagridview1 as the first table (the shyman table) of the data set Ds. You can also write Ds. Table ["shyman"]
Datagridview1.datasource = Ds. Tables [0];
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );//Capture exceptions
}
}
}
The running result is as follows: