EPPlus:如何在Excel中查找整行是否为空

6

我正在使用EPPlus库在我的.net core web api中。在该方法中,我想验证上传的excel文件。我想找出整行是否为空。我有以下代码:

using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
    int rowCount = worksheet.Dimension.End.Row;
    int colCount = worksheet.Dimension.End.Column;

    //loop through rows and columns
    for (int row = 1; row <= rowCount; row++)
    {
        for (int col = 1; col <= ColCount; col++)
        {
            var rowValue = worksheet.Cells[row, col].Value;
            //Want to find here if the entire row is empty
        }
    }
}

如果特定单元格为空,rowValue将告诉我。是否可能检查整行并在为空时继续下一行?
4个回答

5

您可以使用 LINQ 检查行单元格范围的值:

var startRow = 1;
var endRow = 1;
var columnStart = 1;
var columnEnd = worksheet.Cells.End.Column;

var cellRange = worksheet.Cells[startRow, columnStart , endRow, columnEnd];

var isRowEmpty = cellRange.All(c => c.Value == null)

3
感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。一个适当的解释将极大地提高其长期价值,因为它能展示为什么这是一个好的问题解决方案,并使它对未来读者在其他类似问题上更加有用。请编辑您的答案添加一些解释,包括您所做出的假设。 - Syscall

1
你可以在行级别的for循环中设置一个布尔值。然后遍历所有单元格,并在单元格不为空时更改布尔值。
//loop through rows and columns
for (int row = 1; row <= rowCount; row++)
{
    //create a bool
    bool RowIsEmpty = true;

    for (int col = 1; col <= colCount; col++)
    {
        //check if the cell is empty or not
        if (worksheet.Cells[row, col].Value != null)
        {
            RowIsEmpty = false;
        }
    }

    //display result
    if (RowIsEmpty)
    {
        Label1.Text += "Row " + row + " is empty.<br>";
    }
}

这个可以运行。但是当文件有超过100行和10列时,处理需要相当长的时间。 - Thamarai T

1
如果您不知道要检查的列数,可以利用这样一个事实,即Worksheet.Cells集合仅包含实际具有值的单元格条目:
[TestMethod]
public void EmptyRowsTest()
{
    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.AddRange(new[] { new DataColumn("Col1", typeof(int)), new DataColumn("Col2", typeof(int)), new DataColumn("Col3", typeof(object)) });

    //Only fille every other row
    for (var i = 0; i < 10; i++)
    {
        var row = datatable.NewRow();
        if (i % 2 > 0)
        {
            row[0] = i;
            row[1] = i * 10;
            row[2] = Path.GetRandomFileName();
        }
        datatable.Rows.Add(row);
    }

    //Create a test file
    var existingFile = new FileInfo(@"c:\temp\EmptyRowsTest.xlsx");
    if (existingFile.Exists)
        existingFile.Delete();

    using (var pck = new ExcelPackage(existingFile))
    {
        var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
        worksheet.Cells.LoadFromDataTable(datatable, true);

        pck.Save();
    }

    //Load from file
    using (var pck = new ExcelPackage(existingFile))
    {
        var worksheet = pck.Workbook.Worksheets["Sheet1"];

        //Cells only contains references to cells with actual data
        var cells = worksheet.Cells;
        var rowIndicies = cells
            .Select(c => c.Start.Row)
            .Distinct()
            .ToList();

        //Skip the header row which was added by LoadFromDataTable
        for (var i = 1; i <= 10; i++)
            Console.WriteLine($"Row {i} is empty: {rowIndicies.Contains(i)}");
    }
}

输出结果如下(第0行为列标题):

Row 1 is empty: True
Row 2 is empty: False
Row 3 is empty: True
Row 4 is empty: False
Row 5 is empty: True
Row 6 is empty: False
Row 7 is empty: True
Row 8 is empty: False
Row 9 is empty: True
Row 10 is empty: False

刚试了一下,发现这不是真的。除非它还使用单元格格式数据来验证,否则我得到了400行,其中仅有2行是手动输入的。 - Captain Prinny
@CaptainPrinny,你确认那其他398行是真的“空”的了吗?也就是说,这些单元格中有没有空字符串或其他类型的null值?如果你在Excel中按下ctrl+end键,可以看到是否会跳到第400行,如果是,那么说明你的表格中存在空白处。 - Ernie S

1
您可以使用 worksheet.Cells[row, col].count() 方法来实现此操作。如果该行为空,则该方法将返回 0。

1
这只会给你一个单独的单元格,计数为0或1。你需要使用cells[fromRow, fromCol, toRow, toCol]寻址格式,它可以给你一系列的单元格。 - seekingtheoptimal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接