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

标签 c# excel apache-poi npoi

嗯,我正在尝试从 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/

相关文章:

c# - Fluent Nhibernate where 子句一对多

c# - ASP.NET MVC 创建一个包含每个用户列表的变量?

vba - 如何在 Excel UDF 中强制使用参数

java - 验证文件的完整性

java - 替代已弃用的 getCellType

java - 将 8 位索引颜色转换为 RGB

c# - 如何使用 Marshal.getActiveObject() 获取正在运行的进程的 2 个实例,该实例有两个打开的进程

c# - Azure 服务总线作为 Web 作业抛出错误提供的锁无效

Excel字符串转时间格式

vba - 确定变量的完整类型