4

Following is my Person Class

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }       
}

Following is my Code that tries to Read from ExcelSpreadSheet using LinqToExcel DLL

public void UseLinqToExcel(string path)
{

    var excel = new ExcelQueryFactory();  
    excel.FileName = path;
    excel.DatabaseEngine = LinqToExcel.Domain.DatabaseEngine.Ace;

    //Use Explicit Mapping
    excel.AddMapping<Person>(x => x.Name, "Name");
    excel.AddMapping<Person>(x => x.Age, "Age");
    excel.AddMapping<Person>(x => x.Gender, "Gender");            
    var bob = from x in excel.Worksheet<Person>("Bob1")
                        select x;
}

Following is the Code that calls the above method

public void ReadFromExcelSpreadSheet()
{           
    UseLinqToExcel(@"C:\temp\people.xls");
}

Here is the Sample of My ExcelSpreadSheet data.

Name     Age  Gender
----     ---  ------
John     23   Male
Shannon  22   Female 
Joseph   21   Male

The problem is when i set my breakpoint to this line var bob = from x in excel.Worksheet("Bob1") i can see the object bob being filled in with some data. However Only Gender Values are being picked and filled in. The Name and Age values are retrieved as null ad 0 respectively. Could anyone please help me out in fixing this? Thank you

i3arnon
  • 113,022
  • 33
  • 324
  • 344
Sike12
  • 1,232
  • 6
  • 28
  • 53

1 Answers1

3

Since the property and column names are exactly the same, you don't need to perform any mapping with AddMapping()

My guess as to why the Name and Age values are not being returned is there might be extra spaces before or after the column names in the spreadsheet.

You can use the GetColumnNames() method to retrieve the list of column name. (here's the documentation for that method: https://github.com/paulyoder/LinqToExcel#query-column-names)

Paul
  • 18,349
  • 7
  • 49
  • 56
  • I didn't have any leading or trailing spaces. I removed and re-added the columns to see if that worked. Now it works fine. Thank you for that. With the GetColumnNames() i get an exception with the following message ("An exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll but was not handled in user code. External table is not in the expected format). I tried with both Ace and Jet database engines but i get the same message when i try to access the column names – Sike12 Dec 20 '13 at 19:48