Read data from an Excel table to the datagridview.

Source: Internet
Author: User

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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.