Search code examples
c#excellinqlinq-to-excel

LinqToExcel C# - How to NOT read empty row


I want to read data from an excel table that looks like this: Excel Table Screenshot

Worksheet name is "Data". I store the data into List<ExcelData>. Then I do a List.Count, and it is more than 11 even though I only have 11 non-empty rows.

    public class ExcelData
    {
        public string Id { get; set; }
        public string FgCmd { get; set; }
        public string SwCmd { get; set; }
    }

    public void PrintExcelTable()
    {
        var excelFile = new ExcelQueryFactory(@"C:\sample.xlsx");

        var tableData = from z in excelFile.Worksheet<ExcelData>("Data")
                        select z;

        var List = tableData.ToList<ExcelData>();

        Console.WriteLine(List.Count);
    }

I want my List to store only the non-empty row. Any workaround? Preferably be solved during the LinQ selection, not by removing empty data from List after.


Solution

  • Try putting a where clause :

    from z in excelFile.Worksheet<ExcelData>("Data") where z.id != ""
                            select z;