3

我有一个使用ExcelReaderFactory. 但是当有空行/列时,我们就会面临问题。以下是我的原始代码:

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

它产生了两个问题:

  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;

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

如何删除空列?

请找到下面的图片以供参考。 在此处输入图像描述

4

1 回答 1

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

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

于 2018-05-18T11:51:04.220 回答