【问题标题】:Excel.Range throws null even when !=null is checked即使选中 !=null,Excel.Range 也会抛出 null
【发布时间】:2017-12-31 12:14:06
【问题描述】:

当所有单元格都填满时,我会加载 Excel 工作表,没有问题。 但是一个单元格是空的,我得到了一个例外(它的德语,对此感到抱歉):

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:死 Laufzeitbindung kann für einen NULL-Verweis nicht ausgeführt werden.
bei CallSite.Target(Closure , CallSite , Object )

好的,我想应该没问题,所以我检查单元格值是否为空:

for (row = 2; row <= range.Rows.Count; row++)  // Start at Row 2 to Ignore Headrow
{
    DataRow dr = dt.NewRow();
    for (column = 1; column <= range.Columns.Count; column++)
    {
        try
        {
            if(((Excel.Range)range.Cells[row, column]).Value2.ToString() != null)
            {
                dr[column - 1] = ((Excel.Range)range.Cells[row, column]).Value2.ToString();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Error " + column.ToString()); //Always Error when Cell is empty
            Console.WriteLine(e);

        }
    }

    sendConsole("Accept Row " + row + " of " + range.Rows.Count);
    dt.Rows.Add(dr);
    dt.AcceptChanges();
}

但我仍然得到“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”进行空检查。

【问题讨论】:

  • 您必须在调用 ToString() 之前检查 null。您无法访问 null 上的属性或调用方法。
  • 哇!我真的认为这次我的问题不是“菜鸟问题”。非常感谢!!!

标签: c# excel exception


【解决方案1】:

您的代码(第 8 行)中的 Value2 为空。对空对象调用 ToString 将引发空引用异常。就像在空对象上调用任何实例方法一样。对对象进行空检查,然后对其调用 ToString

【讨论】:

    猜你喜欢
    • 2011-07-24
    • 1970-01-01
    • 2012-08-26
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 2023-03-22
    相关资源
    最近更新 更多