Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

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

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.

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

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

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"

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

Can anyone suggest how to do it please?

Here is my code...

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()
                });
            }
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...