skip first row in read of Excel file

后端 未结 4 510
春和景丽
春和景丽 2020-12-17 02:43

Hello I\'m trying to translate an Excel file to my dataGridView and it\'s having column name issues because the way the Excel file is formatted, there are two setup cells fo

相关标签:
4条回答
  • 2020-12-17 03:22

    Just like Thit Lwin has commented. Remove first row before set dt as datasource.

    DataRow row = dt.Rows[0];
    dt.Rows.Remove(row);
    techGrid.DataSource = dt;
    
    0 讨论(0)
  • 2020-12-17 03:23

    The correct method is to tell Excel exactly where in the worksheet to find your column headers and data. Importing the entire sheet and trying to reconstruct your headers from an arbitrary data row is asking for serious trouble. OPENQUERY does not guarantee row order. In testing it will appear to always import in order, but as soon as you move it to a system with a multi-volume tempdb or a heavily loaded production system, your imports will no longer be ordered, and your code will be trying to interpret your data as column headers.

    instead of:

    string query = String.Format("select * from [{0}$]", "Sheet1");
    

    use:

    string query = String.Format("select * from [{0}${1}]", "Sheet1","A2:ZZ");
    

    EDIT: use "A2:end" instead of "A2:ZZ".

    0 讨论(0)
  • 2020-12-17 03:28

    There is an easier way than programatically removing the rows, use the header row property of the connection string. This should skip the first row for you and you can then do what you do with the rest of the rows from there. From ConnectionStrings.com:

    Provider=Microsoft.ACE.OLEDB.12.0; Data Source=myOldExcelFile.xls; 
    Extended Properties="Excel 12.0;HDR=YES";
    

    "HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.

    0 讨论(0)
  • 2020-12-17 03:32

    You can skip as many rows you want like this

    IEnumerable<DataRow> newRows = dt.AsEnumerable().Skip(numberOfRows);
    DataTable  dt2 = newRows.CopyToDataTable();
    
    0 讨论(0)
提交回复
热议问题