Home » excel » c# – Check names in excel row is same as table column names

c# – Check names in excel row is same as table column names

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a code for reading values from excel and insert in to table.I select the first row as the column names of the table.Here I want to check whether the names in the first row of excel sheet is same as table column names?
here is my code for reading excel.

FileStream stream = 
    File.Open(Server.MapPath("~/App_Data/YoutubeVideo/" + fileName), 
    FileMode.Open, FileAccess.Read);

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
excelReader.Close();

dt = result.Tables[0];
dt = dt.Rows.Cast<DataRow>()
            .Where(row => !row.ItemArray.All(field => field is System.DBNull))
            .CopyToDataTable();

Thanks in advance for help….

How to&Answers:

To check before copying the data to the dataset, use excelReader.GetName(0) to get the name of the first column.

Edit:

It seems you are using Excel Data Reader which apparently doesn’t implement all methods from IDataReader.

Since this is not a fully implemented data provider, ou will have to check for the name after loading into a DataTable.

In this case, you can use if (dt.Columns[0].ColumnName == "Name").