gpt4 book ai didi

c# - POI 检查单元格是否为空?

转载 作者:行者123 更新时间:2023-12-04 21:21:44 31 4
gpt4 key购买 nike

嗯,我正在尝试从 Excel 工作表中读取单元格。如果单元格没有值或为空,它将返回 false。我尝试了“null ”( sheet.getrow(a).getcell(b) == nullsheet.getrow(a).getcell(b).celltype == celltype.Blank ),但是当单元格有空格或填充颜色时,它会返回 false

谢谢,我已经被这个问题困扰好几天了。 (如果您需要代码我可以编辑它)。

最佳答案

单元格是否为“空”部分取决于单元格是否实际存在(即不为空)、单元格的类型(字符串/数字/空白等)以及单元格中的值,具体取决于它的类型。我会做一些扩展方法来使这个决定变得更容易。您可以根据需要调整它们以使其工作。例如,如果您认为没有值但填充颜色的单元格非空,则可以在 IsNullOrEmpty 方法内添加对此的检查。

public static class NpoiExtensions
{
public static bool IsCellNullOrEmpty(this ISheet sheet, int rowIndex, int cellIndex)
{
if (sheet != null)
{
IRow row = sheet.GetRow(rowIndex);
if (row != null)
{
ICell cell = row.GetCell(cellIndex);
return cell.IsNullOrEmpty();
}
}
return true;
}

public static bool IsNullOrEmpty(this ICell cell)
{
if (cell != null)
{
// Uncomment the following lines if you consider a cell
// with no value but filled with color to be non-empty.
//if (cell.CellStyle != null && cell.CellStyle.FillBackgroundColorColor != null)
// return false;

switch (cell.CellType)
{
case CellType.String:
return string.IsNullOrWhiteSpace(cell.StringCellValue);
case CellType.Boolean:
case CellType.Numeric:
case CellType.Formula:
case CellType.Error:
return false;
}
}
// null, blank or unknown
return true;
}
}

有了这些方法,您的代码就会变得更加简单:

if (sheet.IsCellNullOrEmpty(a, b))
{
Console.WriteLine("Cell at row " + a + " column " + b + " is empty.");
}

关于c# - POI 检查单元格是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820990/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com