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

use*_*677 6 c# excel epplus

我在 .net core Web api 中使用 EPPlus 库。在上述方法中我想验证他上传的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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的 rowValue 会告诉我特定单元格是否为空。是否可以检查整行,如果为空则继续到下一行。

Ale*_*aro 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)
Run Code Online (Sandbox Code Playgroud)

  • 感谢您提供此代码片段,它可能会提供一些有限的即时帮助。正确的解释将通过展示为什么这是解决问题的良好解决方案来极大地提高其长期价值,并使其对未来有其他类似问题的读者更有用。请编辑您的答案以添加一些解释,包括您所做的假设。 (3认同)

VDW*_*WWD 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>";
    }
}
Run Code Online (Sandbox Code Playgroud)