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
}