检查Cell是否为空以在循环时断开

时间:2016-05-24 11:31:01

标签: c# excel-interop

您好我正在研究从Cells中提取数据的方法。这有效,但每当我到达一个空单元格时,我都会得到一个NullBinderException

我的问题是如何防止这种情况?

以下是造成问题的部分:

    while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
    {
        for (int i = 1; i <= numberOfColumns; i++)
        {
            string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
            stringList.Add(sValue);
            cell++;
        }
        startpoint++;
        cell = 1;
    }

我试过的东西:

range.Offset =不能使用因为这不是一个可行的会员 IsNullOrEmpty =没有区别

所以有些东西我无法得到。任何帮助或建议都会很棒,谢谢你的时间。

3 个答案:

答案 0 :(得分:1)

您可以将while循环设为: -

while (! IsNull(range.Cells[startpoint, cell] as Excel.Range).Value2))

答案 1 :(得分:1)

Cell Range和/或Value2可以为null。在Where子句中检查这些。

while ((range.Cells[startpoint, cell] as Excel.Range) != null && (range.Cells[startpoint, cell] as Excel.Range).Value2 != null)
{
    for (int i = 1; i <= numberOfColumns; i++)
    {
        string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
        stringList.Add(sValue);
        cell++;
    }
    startpoint++;
    cell = 1;
}

答案 2 :(得分:0)

您可以尝试捕获异常,例如:

try
{
  while ((range.Cells[startpoint, cell] as Excel.Range).Value2.ToString() != null)
  {
    for (int i = 1; i <= numberOfColumns; i++)
    {
        string sValue = (range.Cells[startpoint, cell] as Excel.Range).Value2.ToString();
        stringList.Add(sValue);
        cell++;
    }
    startpoint++;
    cell = 1;
  }
}
catch(nullBinderException e)
{
   //you find an empty cell
   //... break? jump over and continue?
   //... your logic...
}