Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get excel sheet column names using exceldatareader

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?

like image 356
venkat Avatar asked Jan 11 '17 12:01

venkat


1 Answers

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()
                          });
like image 151
Galilo Galilo Avatar answered Oct 18 '22 19:10

Galilo Galilo