I have a process to import data from excel to DB using ExcelReaderFactory
. But when there is empty rows/column, we are facing issue. Below is my original code:
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileContent);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTable dataTable = result.Tables[0].Rows
It creates 2 issues:
If there is empty rows in end, they will be there in datatable.
If there is empty colmns in the end, they will be there in datatable.
Is there any way to remove both empty rows and column. I can remove empty rows from datatable using below code
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileContent);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTable dataTable = result.Tables[0].Rows
.Cast<DataRow>()
.Where(row => !row.ItemArray.All(field => field is DBNull ||
string.IsNullOrWhiteSpace(field as string ?? field.ToString())))
.CopyToDataTable();
return dataTable;
But it will not remove empty columns. Is there a better way to do it?
How to remove also empty columns?