1

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();

1 Answer 1

6

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.

enter image description here

Sign up to request clarification or add additional context in comments.

5 Comments

Because that way the headers from excel don't get put into the data table as headers
are the no. of junk lines fixed in your sheet?
I have updated the answer. Please check if that works for you. I have run it locally and it seems to do what you ask for.
That seems to get the headers but not the data
It does get the data too. What is the row count you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.