Generating C# Classes from Excel

A while back I was tasked with converting and migrating data from an existing accounting system to a new one, (un)fortunately this was not the first time I was asked to do a data conversion. A year prior I had to migrate data from a 20 year old legacy system to a new software solution.

While the systems were completely different I was able to reuse a lot of the patterns and helper libraries which I had used before. During the first data conversion I felt a large portion of my time was wasted creating classes for the corresponding excel input and output files. I thought if I could generate classes with properties corresponding to the excel columns and their types, that it might save some unnecessary typing to create those classes.

So i created ExcelToClasses, a NuGet package which will open an .xls file and convert each worksheet to a class and each column to a property within that class.

The NuGet package can be found here:

https://www.nuget.org/packages/ExcelToClasses/

The package will add some T4 templates to your project, all that’s needed is to open the DataConversion.tt file and supply one or many paths to the excel file(s) and save the DataConversion.tt file.

A .cs file will be generated per worksheet, each property will have an attribute with the name and position of the corresponding excel column. This will be very useful if you are generating classes for the output schema (the format of the new system) and you wish to rename the properties or change their position in the class without affecting the output file to be generated.

Github:

https://github.com/OmarElabd/ExcelToClasses

Enjoy

Omar Elabd

Omar Elabd

Omar Elabd is a software developer specializing within the .NET Framework. He has experience in developing Web and Desktop based applications using ASP.NET, MVC, WebAPI and WPF.
Omar Elabd
  • Danny Rodriguez

    Very nice. Thank you very much for sharing … I had searched for something like this a year ago and it didn’t exist.

    • http://www.omarelabd.net/ Omar Elabd

      Glad you it was useful to you, thanks for the comment @disqus_8wAujj3ad8:disqus. I’m also working on a webservice where you can upload an excel file directly ( https://github.com/OmarElabd/ExcelToClassesWeb ).

  • Alejandro Quiroz

    Man, I got a similar problem with some formats made in excel, so I don’t have column headers but I do have labels for the fields, is there a way to adapt your code to take those fields instead?