简体   繁体   中英

How to SELECT from any spreadsheet in Excel File using OleDbDataAdapter

I'm using OleDbDataAdapter to extract DataSet from excel file, but I have problems with SELECT statement inside

DataSet excelDataSet = new DataSet();
using (OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString))
{
     con.Open();
     OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter("select * from [Name of spreadsheet]", con);
     cmd.Fill(excelDataSet);
     con.Close();
}

If you see I have "select * from [Name of spreadsheet]" , but I need to get any spreadsheets, or for example 1st spreadsheet, but the name for this spreadsheet can be anything.

How to specify it? Is it any special characters like "select * from [%]"

You need to know the name of the sheet to apply the select statement at it.
And you need to add the special char $ at the end of the name.

Supposing you have a sheet named MyFirstSheet then you can select rows from it with

 OleDbDataAdapter cmd = new OleDbDataAdapter("select * from [MyFirstSheet$]", con);

In case you don't know the names of your sheets you could call

using (OleDbConnection con = new OleDbConnection(connectionString))
{
    con.Open();
    DataTable dt = con.GetSchema("Tables");
    string firstSheet = dt.Rows[0]["TABLE_NAME"].ToString();
    ...... work with the first sheet .....
}

This example should give you the name of the first sheet in the excel file (other sheets are available in the successive rows after the first)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM