get excel sheet column names using exceldatareader

venkat picture venkat · Jan 11, 2017 · Viewed 8.8k times · Source

I'm writing the C# library to read the Excel Files without any other dependencies like OLDEB(AccessDatabaseEngine) library.

So I have chosen the ExcelDataReader Library for Reading the .XLS and .XLSX files.

ExcelDataReader is perfectly working with both file formats with my local and deployment server environment.

I'm facing issue, how to get all the columns names from given Excel files?

Answer

Galilo Galilo picture Galilo Galilo · Feb 24, 2020

The same answer of @Kevin, but need to set ExcelDataReader to use header row as column titles. the code will look like the following:

var stream = File.Open(@"C:\temp\Book1.xlsx", FileMode.Open, FileAccess.Read);

var excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

var result = reader.AsDataSet(new ExcelDataSetConfiguration() {
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() {
    UseHeaderRow = true
}
});

var tables = result.Tables
                   .Cast<DataTable>()
                   .Select(t => new {
                                     TableName = t.TableName,
                                     Columns = t.Columns
                                                .Cast<DataColumn>()
                                                .Select(x => x.ColumnName)
                                                .ToList()
                          });