Search code examples
c#excelasp.net-coredatatableexceldatareader

How to read only columns from Excel using ExcelDataReader?


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.


Solution

  • 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));
    }