Question

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.

Était-ce utile?

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

Autres conseils

but somehow LinqToExcel reads them as well

This is a quirk of Excel. It remembers how many rows and columns where used when the Sheet was at it largest size. You can see this by typing Ctrl-End. This will select the cell in the last row and column ever used.

Office support describes how to reset the last cell: Locate and reset the last cell on a worksheet

Basically, you delete excess rows and columns, clear formatting, save the workbook and reopen it.

This work-around could be useful if you have Excel-files waiting to be imported and no time to deploy your fixed Linq2Excel client.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top