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

Cannot perform runtime binding on a null reference - Empty Excel Cells

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

我正在尝试将 excel 电子表格的行读入 object。

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

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

我只是不知道在哪里可以放置一些 "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()
                });
            }
        }
    }

您在调用 ToString 之前需要它们。也许你甚至可以在添加之前移动 if ,因为我认为添加空行没有用,但在你的场景中这可能是正确的:

if (row.Cells[i + 1, 1].Value2 != null && row.Cells[i + 1, 2].Value2 != null)
{
    spreadsheetrows.Add(new SPREADSHEETModel.spreadsheetRow()
    {
        col1 = row.Cells[i + 1, 1].Value2.ToString(),
        col2 = row.Cells[i + 1, 2].Value2.ToString()
    });
}

否则这可能是您需要的:

col1 = row.Cells[i + 1, 1].Value2 != null ? row.Cells[i + 1, 1].Value2.ToString() : null,

异常背后的原因是 Value2dynamic,因此 return 值是在运行时确定的。而如果Value2null,则无法确定要调用的ToString方法

不要使用.ToString()当值为null时会导致null reference exception。 使用 Convert.ToString(),它将 return 空字符串作为空值。

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

你可以在 for 循环中检查:

    //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()
            {
        if (row.Cells[i + 1, 1].Value2 != null)
        {                       
            col1 = row.Cells[i + 1, 1].Value2.ToString();
        }
        if (row.Cells[i + 1, 2].Value2 != null)
        {
                        col2 = row.Cells[i + 1, 2].Value2.ToString();
        }
        if (row.Cells[i + 1, 3].Value2 != null)
        {
                        col3 = row.Cells[i + 1, 3].Value2.ToString();
        }
            });
        }
    }