How to obtain the first sheet name when importing an Excel file

Source: Internet
Author: User
How can I get the names of sheet in Excel? In this way, you can dynamically select the sheet data to be returned. Even if you have changed the name, you can list all sheet names for the user to choose from: Code

/// <Summary>
/// Extract the table data according to the path of the Excel file
/// </Summary>
/// <Param name = "path"> Excel file path </param>
Private void getdatafromexcelwithappointsheetname (string path)
{
// Connection string
String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + path + ";" + "extended properties = Excel 8.0 ;";
Oledbconnection conn = new oledbconnection (strconn );

Conn. open ();

// Return the Excel schema, including the name, type, Creation Time, and modification time of each sheet.
Datatable dtsheetname = conn. getoledbschematable (oledbschemaguid. Tables, new object [] {null, "table "});

// String array containing the table name in Excel
String [] strtablenames = new string [dtsheetname. Rows. Count];
For (int K = 0; k <dtsheetname. Rows. Count; k ++)
{
Strtablenames [k] = dtsheetname. Rows [k] ["table_name"]. tostring ();
}

Oledbdataadapter mycommand = NULL;
Datatable dt = new datatable ();

// Query data from the specified table. All the table columns can be selected first.
String strexcel = "select * from [" + strtablenames [0] + "]";
Mycommand = new oledbdataadapter (strexcel, strconn );
Dt = new datatable ();
Mycommand. Fill (DT );

Datagridview1.datasource = DT; // bind to the interface
}

 

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.