ldn*_*ldn 1 c# excel apache-poi npoi
好吧,我正在尝试从 Excel 工作表中读取单元格。如果单元格没有值或为空,它将返回 false。我试过“ null”(sheet.getrow(a).getcell(b) == null和sheet.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;
}
}
Run Code Online (Sandbox Code Playgroud)
有了这些方法,您的代码就会变得更加简单:
if (sheet.IsCellNullOrEmpty(a, b))
{
Console.WriteLine("Cell at row " + a + " column " + b + " is empty.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2928 次 |
| 最近记录: |