Sunday, June 5, 2016

Loading Excel (.xlsx) files in C#

So I needed to write an app (console) that would read and process an excel file. A quick search would lead me to this stackoverflow post which suggests using the Linq-To-Excel package.

Linq-To-Excel has a Nuget package and is easily installed. This nice little snippet in that post is self explanatory:

var data= new LinqToExcel.ExcelQueryFactory(@"MyFile.xlsx");

var query =
    from row in data.Worksheet("MySheet")
    let item = new
    {
        Id = row["Id"].Cast<string>(),
        Name= row["Name"].Cast<string>(),
        Age= row["Age"].Cast<int>(),
    }
    select item;

    foreach ( var item in query) {
        Console.Writeline(item.Id "\t" item.Name);
    }

Except that the following run time exception will be thrown when you start iterating through the results (the microsoft.ace.oledb.12.0 provider is not registered)


This is easily resolved by installed the Microsoft Access Database engine from this page : - and there you go - load up any excel file just like any simple TSV!

No comments:

Post a Comment