简体   繁体   中英

C# reading excel file where the header is not the first row

I'm trying to read data from an excel file. Full code below. The first few lines are junk, so skip them using the following

"SELECT * From [" + SheetName + "] WHERE [F3] <> ''";

I want to read the code to a datatable and still keep the headers. which appear after the junk lines.

The problem is that when I filter our the junk lines using the WHERE clause above, the datatable column titles come out as F1,F2 etc

In my connection string I do specify I want the headers

HDR=Yes.

If I remove the WHERE clause from the SELECT, it works as I expect.

Please advise

switch (Extension)
            {
                case ".xls": //Excel 97-03
                    conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                    break;
                case ".xlsx": //Excel 07
                    conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                    break;
            }
            conStr = String.Format(conStr, FilePath, "Yes");
            OleDbConnection connExcel = new OleDbConnection(conStr);
            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            cmdExcel.Connection = connExcel;

            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = ListSheets.SelectedValue;
            connExcel.Close();

            //Read Data from First Sheet
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + SheetName + "] WHERE [F3] <> ''";
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);


     connExcel.Close();

Assuming you have fixed lines of junk code in your Excel Sheet, you could execute the query like this.

"SELECT * From [Sheet1$A5:C]"

The assumption here is that your headers are on line 5 and C is the column where your data ends. This correctly loads the header names for the columns.

Adding a snapshot of the Excel against which the above query works.

在此处输入图片说明

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