.NET Power Tip 3: Reading Data from Excel/CSV

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:

  1. Add the nuget package “LinqToExcel” to your project.
  2. (if you get a log4net version conflict, upgrade your log4net nuget package)
  3. Watch the introduction video: https://www.youtube.com/watch?v=t3BEUP0OTFM
  4. Follow the instructions at: https://github.com/paulyoder/LinqToExcel

Example file:

image

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:

image

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/