无法对空引用执行运行时绑定 - 清空Excel单元格

Tre*_*iel 9 .net c# excel vsto

我似乎无法想出一种方法来纠正标题中提到的错误,并且正在寻找关于应该做什么的一些想法.

我试图将excel电子表格的行读入对象.

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

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

我无法解决我可以在哪里进行"if null"检查.

谁能建议怎么做呢?

这是我的代码......

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()
                });
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sar*_*mar 28

当值为null时,不要使用.ToString()null reference exception.使用时Convert.ToString(),它将为空值返回空字符串.

col1 = Convert.ToString(row.Cells[i + 1, 1].Value2);
col2 = Convert.ToString(row.Cells[i + 1, 2].Value2);
Run Code Online (Sandbox Code Playgroud)