LinqToExcel blank rows

假装没事ソ 提交于 2020-01-14 22:47:51

问题


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.

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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/14738313/linqtoexcel-blank-rows

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!