如何从数据表中删除空行和多余列

问题描述 投票:0回答:2

我有一个使用

ExcelReaderFactory
将数据从Excel导入到数据库的过程。但是当有空行/列时,我们就会遇到问题。以下是我的原始代码:

IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(fileContent);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();                    
DataTable dataTable = result.Tables[0].Rows

它产生了 2 个问题:

  1. 如果最后有空行,它们将存在于数据表中。

  2. 如果最后有空列,它们将存在于数据表中。

有什么方法可以删除空行和空列。 我可以使用下面的代码从数据表中删除空行

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;

但它不会删除空列。 有更好的方法吗?

如何删除空列?

请参阅下图以供参考。

c# excel datatable excel-reader
2个回答
4
投票

您可以使用此扩展程序:

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

如果您想从给定的索引开始,请将其传递给方法。


0
投票

要回答完整问题,包括删除空白行,请使用此扩展:

        public static void RemoveEmptyColumnsAndRows(this DataTable table)
        {
            foreach (var column in table.Columns.Cast<DataColumn>().ToArray())
            {
                if (table.AsEnumerable().All(dr => dr.IsNull(column) || string.IsNullOrWhiteSpace(dr[column].ToString())))
                    table.Columns.Remove(column);
            }
            foreach (var row in table.Rows.Cast<DataRow>().ToArray())
            {
                if (row.ItemArray.All(field => field is DBNull || string.IsNullOrWhiteSpace(field as string)))
                    table.Rows.Remove(row);
            }
        }

要排除用户定义的列,请在列数组上的

Where
之前添加此
.ToArray()

.Where(col=>col.ColumnName.StartsWith("Column"))
© www.soinside.com 2019 - 2024. All rights reserved.