How to read only columns from Excel using ExcelDataReader?

634 Views Asked by At

I am using below code to read column names from Excel sheet. It's working fine. But it loads entire sheet data into datatable. It takes a lot of time. Is there any way we can read only column names and not load whole sheet?

   using (var stream = File.Open(strDoc, FileMode.Open, FileAccess.Read))
   { 

        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            dt = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (tablereader) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
            }).Tables["Data"];
        }
    }

    foreach (var col in dt.Columns)
    {
        columnNamesList.Add(col.ToString().Trim());
    }

'Data' is the sheet name.

2

There are 2 best solutions below

2
user8728340 On BEST ANSWER

The fastest is to read the first row without the overhead of AsDataSet:

for (int i = 0; i < reader.FieldCount; i++) {
    columnNamesList.Add(reader.GetString(i));
}
1
Chen On

You can use FilterRow to skip rows. For example:

dt = reader.AsDataSet(new ExcelDataSetConfiguration()
{
     ConfigureDataTable = (tablereader) => new ExcelDataTableConfiguration() { UseHeaderRow = true, FilterRow = rowReader => rowReader.Depth < 1 }
}).Tables["Data"];

At this point dt.Rows.Count will be 0.

Not sure if this will speed up the response, but it prevents rows from the sheet from being inserted into the DataTable.

Helpful links:

Using ExcelDataReader to read Excel data starting from a particular cell.

How skip rows and cells to create the dataset?.