无法在空引用上执行运行时绑定 - 空Excel单元格 [英] Cannot perform runtime binding on a null reference - Empty Excel Cells

查看:774
本文介绍了无法在空引用上执行运行时绑定 - 空Excel单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎没有想到要纠正标题中提到的错误,并且正在寻找一些关于应该做什么的想法。

I cannot seem to think of a way to correct the error mentioned in the title and was looking for some ideas on what should be done.

我正在尝试将excel电子表格的行读入一个对象。

I am trying to read the rows of a excel spreadsheet into an object.

第一次循环我没有问题,因为行1,列1和行1列2中有数据。

The first time it loops I have no problems because row 1, column 1 and row 1 column 2 have data in them.

但是当它到达第2行,第1列和第2列时,它会因上述错误而崩溃,因为电子表格中的这些单元格为空

But when it gets to row 2, column 1 and row 2 column 2 it falls over with the above error because those cells in spreadsheet are "empty"

我只是无法找出我可以放入一些if null支票。

I just cannot work out where I can put some "if null" checks in.

任何人都可以建议如何做这是吗?

Can anyone suggest how to do it please?

这是我的代码...

private static void IterateRows(Excel.Worksheet worksheet)
    {
        //Get the used Range
        Excel.Range usedRange = worksheet.UsedRange;

        // create an object to store the spreadsheet data
        List<SPREADSHEETModel.spreadsheetRow> spreadsheetrows = new List<SPREADSHEETModel.spreadsheetRow>();

        //Iterate the rows in the used range
        foreach (Excel.Range row in usedRange.Rows)
        {
            for (int i = 0; i < row.Columns.Count; i++)
            {
                spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow()
                {
                    col1 = row.Cells[i + 1, 1].Value2.ToString(),
                    col2 = row.Cells[i + 1, 2].Value2.ToString()
                });
            }
        }
    }


推荐答案

当值为null时,不要使用 .ToString()将导致空引用异常
使用 Convert.ToString(),它将为空值返回空字符串。

Do not use .ToString() it will cause null reference exception when the value is null. Use Convert.ToString(), it will return empty string for the null value.

col1 = Convert.ToString(row.Cells[i + 1, 1].Value2);
col2 = Convert.ToString(row.Cells[i + 1, 2].Value2);

这篇关于无法在空引用上执行运行时绑定 - 空Excel单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆