0

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 Answers 2

1

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

How to use this code to read particular sheet in the excel? I am reading sheet named 'Data'.
@SAT The reader object has Name property and NextResult() method to navigate sheets. Could do something like: while (reader.Name != "Data" || reader.NextResult()) {} (untested!)
0

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?.

1 Comment

Thanks. Unfortunately this doesn't improve speed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.