我在 .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 会告诉我特定单元格是否为空。是否可以检查整行,如果为空则继续到下一行。
您可以使用 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)
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)