简体   繁体   中英

c#: Accessing cells in excel worksheet throws NullReferenceException

So I've been trying to write a console application (.Net Core) which reads data from an Excel file but I'm kinda stuck.

I've been trying to get this code sample to work: https://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/

I needed to use (Range)cell explicitly because Visual Studio threw errors when the sample code tried to access the cell directly.

When trying to load the worksheet and the used range m_ObjectToDataMap = null for both worksheet and range. Accessing the rows with excelRange.Rows fails due to System.NullReferenceException: 'Object reference not set to an instance of an object.'

static void Main(string[] args)
{
    //Create COM Objects.
    Application excelApp = new Application();

    if (excelApp == null)
    {
        Console.WriteLine("Excel is not installed!!");
        return;
    }

    Workbook excelBook = excelApp.Workbooks.Open(@"D:\test.xlsx");
    _Worksheet excelSheet = (_Worksheet)excelBook.Sheets[1];
    Range excelRange = excelSheet.UsedRange;

    foreach (Range row in excelRange.Rows)  // Here is the NullReference Error
    {
        // create new line
        Console.Write("\r\n");
        foreach (Range col in excelRange.Columns)
        {
            Range cell = (Range)excelRange.Cells[row, col];
            // write the console
            if (excelRange.Cells[row, col] != null && cell.Value2 != null)
                Console.Write(cell.Value2.ToString() + "\t");
        }
    }
    //after reading, relaase the excel project
    excelApp.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
    Console.ReadLine();
}

I tried a lot of different code, looping through all sheets or calling the sheet by its name but it always ends with worksheet and range being loaded incorrectly and the NullReferenceException.

Any help would be appreciated.

I think the code reference you were using was a console app in .NET Framework. I used the code from here that you referenced and put it in a .NET Framework console application and it works perfectly. I put the same code in a .NET Core console application and it does not work. So you might need to change to .NET Framework or you can use another excel library. I use NPOI which you can follow an example here or do some more googling to find other examples. There is also probably more libraries out there like EPPlus that work in .NET Core for parsing excel but I have not used or looked into any others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM