As with writing data to Excel, reading data can be achieved in multiple ways.
If you need read and write capabilities, check out .NET PowerTip 2: http://www.12qw.ch/2015/09/net-powertip-2-write-data-to-excel/
However, if you just need to read some data, there is a magnificent library to help you out. Meet LinqToExcel https://github.com/paulyoder/LinqToExcel .
How does it work:
- Add the nuget package “LinqToExcel” to your project.
- (if you get a log4net version conflict, upgrade your log4net nuget package)
- Watch the introduction video: https://www.youtube.com/watch?v=t3BEUP0OTFM
- Follow the instructions at: https://github.com/paulyoder/LinqToExcel
Example file:
Example code:
namespace ConsoleApplication3 { public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string Occupation { get; set; } } class Program { static void Main(string[] args) { var excel = new ExcelQueryFactory(); excel.FileName = "coolpeoplelist.xlsx"; //We assume that the properties in person and the columns in //the excel file match var coolPeople = from x in excel.Worksheet<Person>() select x; } } }
Result:
Hint: After installing the Nuget Package for LinqToExcel, the application could not start since the log4net version that was installed and the one that LinqToExcel was looking for did not match. Upgrading the log4net nuget package solved the issue.
All credits for the library go out to: http://blog.yodersolutions.com/