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