Tuesday, September 19, 2017

How do you use LinqToExcel if there are no named columns?

If your columns are just named, A, B, C, etc. then this makes things trickier as these default titles will not be recognized with this trick and thus you cannot do something like this to map the rows to a collection of a custom type. You can however map the rows to a collection of RowNoHeader (which is a type LinqToExcel has) and then loop through the records and make a list of your own custom type like so:

public List<History> GetWeldLogs(string pathToFile)
{
   var excelSheet = new ExcelQueryFactory(pathToFile);
   IQueryable<RowNoHeader> logs = from x in excelSheet.WorksheetNoHeader("Log")
         select x;
   List<History> histories = new List<History>();
   foreach (RowNoHeader log in logs.ToList())
   {
      History history = new History();
      history.Note = log[12].Value.ToString();
      histories.Add(history);
   }
   return histories;
}

 
 

This may look like the thirteenth column is being mapped off to Note, but honestly it will only be the thirteenth column that has data. If there are completely empty columns they will not go into this count and may throw your count off.

No comments:

Post a Comment