linq-to-excel

LinqToExcel blank rows


I am using LinqToExcel to easily import Excel data into SQL Server.

        var fileName = ConfigurationManager.AppSettings["ExcelFileLocation"];
        var excel = new ExcelQueryFactory(fileName);
        var employees = excel.Worksheet<Employee>().ToList();

Everything's fine, there is only 1 problem, the fields mapped exactly to the database table fields, and in the database they are NOT NULL.

Input excel file

Having said that, if you look at this screenshot of Excel file, some rows below row 3 are actually not empty. There are no spaces, but somehow LinqToExcel reads them as well and of course I get exception thrown by EntityFramework saying the field cannot be null.

I need to select all the blank rows below 3 up to 8980 something, and delete them. Only then I can use LinqToExcel not trying to import blank rows.

Any idea how to solve the problem?

Thanks.


Solution

  • You can add a condition to the LINQ statement so the empty rows are not included.

    var employees = excel.Worksheet<Employee>().Where(x => x.VS2012 != null).ToList();
    

    And if checking for not null does not work, then you can check for an empty string

    var employees = excel.Worksheet<Employee>().Where(x => x.VS2012 != "").ToList();