[英]How to remove empty rows and extra columns from datatable
我有一个使用ExcelReaderFactory
将数据从excel导入数据库的过程。 但是,当行/列为空时,我们将面临问题。 下面是我的原始代码:
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileContent);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
DataTable dataTable = result.Tables[0].Rows
它产生2个问题:
如果最后有空行,则它们将存在于数据表中。
如果最后有空的colmn,它们将存在于数据表中。
有什么办法可以删除空行和空列。 我可以使用以下代码从数据表中删除空行
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;
但是它不会删除空列。 有更好的方法吗?
如何删除空列?
您可以使用以下扩展名:
public static void RemoveEmptyColumns(this DataTable table, int columnStartIndex = 0)
{
for (int i = table.Columns.Count - 1; i >= columnStartIndex; i--)
{
DataColumn col = table.Columns[i];
if (table.AsEnumerable().All(r => r.IsNull(col) || string.IsNullOrWhiteSpace(r[col].ToString())))
table.Columns.RemoveAt(i);
}
}
如果要从给定的索引开始,请将其传递给方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.