Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Excel.Range即使在以下情况下也会抛出null=空值被选中_C#_Excel_Exception - Fatal编程技术网

C# Excel.Range即使在以下情况下也会抛出null=空值被选中

C# Excel.Range即使在以下情况下也会抛出null=空值被选中,c#,excel,exception,C#,Excel,Exception,当所有单元格都填满时,我加载Excel工作表,没有问题。 但是如果一个单元格是空的,我得到一个例外(是德语,很抱歉): Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:Die 没有任何证据表明这一点。 bei CallSite.Target(闭包、调用站点、对象) 好的,应该没问题,我想,所以我检查单元格值是否为空: for (row = 2; row <= range.Rows.Count; row++) // Start a

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

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:Die 没有任何证据表明这一点。
bei CallSite.Target(闭包、调用站点、对象)

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

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();
}

代码(第8行)中的for(row=2;rowValue2为null。在null对象上调用ToString将引发null ref异常。在null对象上调用任何实例方法也会引发null ref异常。对该对象执行null检查,然后对其调用ToString

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