首页 > 解决方案 > c#:访问excel工作表中的单元格抛出NullReferenceException

问题描述

所以我一直在尝试编写一个控制台应用程序(.Net Core),它从 Excel 文件中读取数据,但我有点卡住了。

我一直试图让这个代码示例工作:https ://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/

我需要(Range)cell显式使用,因为当示例代码尝试直接访问单元格时,Visual Studio 会抛出错误。

尝试加载工作表和m_ObjectToDataMap = null工作表和范围的使用范围时。使用 excelRange.Rows 访问行因 System.NullReferenceException 失败:“对象引用未设置为对象的实例。”

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

我尝试了很多不同的代码,循环遍历所有工作表或通过其名称调用工作表,但它总是以工作表和范围加载不正确以及 NullReferenceException 结束。

任何帮助,将不胜感激。

标签: c#excel

解决方案


我认为您使用的代码参考是 .NET Framework 中的控制台应用程序。我使用了您引用的此处的代码并将其放入 .NET Framework 控制台应用程序中,它运行良好。我将相同的代码放在 .NET Core 控制台应用程序中,但它不起作用。因此,您可能需要更改为 .NET Framework,或者您可以使用另一个 Excel 库。我使用 NPOI,您可以在此处遵循示例或进行更多谷歌搜索以查找其他示例。可能还有更多像EPPlus这样的库可以在 .NET Core 中用于解析 excel,但我没有使用或研究过任何其他库。


推荐阅读