c# Excel skipping first row?

I’m importing an xls file using OleDbCommand to a ds. Problem I’m having is during the foreach on my ds its skipping for first row. I can’t figure out why. Any suggestions?

cmd.CommandText = string.Format("SELECT * FROM [{0}$]", worksheetName);
conn.Open();

var adapter = new OleDbDataAdapter();
var ds = new DataSet();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
var table = ds.Tables[0];

foreach(DataRow row in table.Rows){ // rest of my code }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Change the connection string (as mentioned in comment) from:

string cnn = string.Format( 
    "Provider=Microsoft.ACE.OLEDB.12.0;" +
    "data source={0}{1}{2};" +
    "Extended Properties=Excel 8.0;", 
    fileLocation, fileName, fileExtension);

to:

string cnn = string.Format( 
    "Provider=Microsoft.ACE.OLEDB.12.0;" +
    "data source={0}{1}{2};" +
    "Extended Properties=Excel 8.0;HDR=No", 
    fileLocation, fileName, fileExtension);

Method 2

Check your connection string. Most likely it contains:

HDR=Yes

which indicates that first row is a header

Method 3

Maybe you’ve told it to skip first row. I remember a property that sounds something like FirstRowIsHeader. I think if that is set to true, then it skips. this can be changed at point you create your connection


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x