Reading Excel files in .Net

This should work for most Excel versions including both xls and xslx:

 
const string ExcelConnString =
                @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES"";";
 
            var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", String.Format(ExcelConnString, physicalPath));
            var ds = new DataSet();
 
            adapter.Fill(ds, "anyNameHere");
            var data = ds.Tables["anyNameHere"].AsEnumerable();
 
            EnumerableRowCollection tags =
                data.Where(x => x.Field("tag") != string.Empty).Select(x =>
                                                                                 new Tag()
                                                                                     {
                                                                                         Description = x.Field("Description")
                                                                                     });

Leave a Reply