【问题标题】:c#: Accessing cells in excel worksheet throws NullReferenceExceptionc#:访问excel工作表中的单元格抛出NullReferenceException
【发布时间】:2019-09-30 11:24:42
【问题描述】:

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

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

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

当尝试为工作表和范围加载工作表和使用的范围 m_ObjectToDataMap = null 时。由于 System.NullReferenceException: 'Object reference not set to an instance of an object.'

使用 excelRange.Rows 访问行失败。
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 结束。

任何帮助将不胜感激。

【问题讨论】:

  • 你可能已经合并了单元格...你还需要释放工作表、范围和工作簿
  • 出于测试目的,我只是将“测试”写入前 6 个单元格(第 1 行中的 3 个和第 2 行中的 3 个),所以 exel 文件应该没问题
  • 我知道 NullReference 是什么,但我找不到如何正确加载工作表(或范围)
  • 你为什么要在每个循环中为单个单元格创建一个新的“范围”,只需读取单元格

标签: c# excel


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 2012-07-08
    • 2014-01-15
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多