Here is a simple snippet which shows how to import data from an excel spreadsheet into your domains objects using c#.
The following code snippets form part of a static helper class called ExcelImport.cs. We make use of generics here, in that we assume the developer is aware of the type of object they are trying to populate from the excel spreadsheet.
Snippet 1 - Static import Class, Parse<K> Method.
Our static class will have a generic method called "Parse<K>". This method, as you can see, is a generic method which takes two parameters (fileName and workSheetName). The method makes use of the OleDbConnection and OleDbDataAdapter ADO classes to in effect "query" the spreadsheets data.
As you can see, this method hands off the actual population logic to a private static method called "PopulateData". Parse<K> hands the type of 'K' down to the PopulateData method along with the new DataSet which has been read from the spreadsheet.
Snippet 2 -PopulateData<T> method.
The PopulateData method instantiates a List<T> ('K' from the Parse<K> method) and iterates through each row in the DataSet. It then uses the Activator.CreateInstance<>() to create a new dto (Of type T). We then hand off to yet another method which uses reflection to map the data to the business object, called PopulateFieldsFromDataRows().
Snippet 2 -PopulateFieldsFromDataRows() method.
Here, we simply reflect over the object and access any public fields, or properties. We then try and populate the objects property/field based on its name.
Below is an example of how the static class is used. I have implemented a CreatenewBusinessObject<> static class here, just to because I think that handing object creation off to a factory is a good thing ;).
Again, a very simple and elegant solution to reading an Excel spreadsheet into your c# application, but one step further. By utilizing the power of Generics and Reflection we can simply hand off the processing to a static helper.
Have Fun !