【问题标题】:Cannot perform runtime binding on null reference C# Excel无法对空引用 C# Excel 执行运行时绑定
【发布时间】:2018-08-20 16:05:27
【问题描述】:

我发现了很多类似的问题,但没有一个能解决我的问题。我正在使用 SSIS 和 C# 脚本来读取和修改 Excel 工作簿的样式。

我收到以下错误“无法对空引用执行运行时绑定”。我理解错误的含义;本质上,您不能使用/引用为空的东西。但我认为我正在检查 IF 语句中的所有 NULL。

我正在使用的代码:

     int rows = xlWorkSheetTY.UsedRange.Rows.Count - 1;
     Excel.Range rge = xlWorkSheetTY.get_Range("J2:J" + rows, System.Type.Missing);
     foreach (Excel.Range item in rge.Cells)
     {
         if (item != null && (item.Value2 != null || item.Value2 != "" || item.Value2 != "NULL"))
         {
              decimal result = (decimal)0.00;
              if (decimal.TryParse(item.Value2.ToString(), out result))
                        {
                            if (result <= 20)
                            {
                                item.Interior.Color = Excel.XlRgbColor.rgbRed;
                                item.Font.Color = Excel.XlRgbColor.rgbWhite;
                            }
                        }
          }
      }

任何人对我为什么会收到此错误以及我可以做些什么来纠正有任何建议?

更新: 我插入了一个try catch 语句来尝试查找有关它失败原因的更多详细信息。它每次都在特定行上失败。我在原始 Excel 文件中查看了这一行,数据为空。

如何防止它解析这个字段而不做我已经拥有的 - 检查 nulls 等?

【问题讨论】:

  • 在代码中打断并单步执行。您可能会收到更好的错误消息
  • 能像拆分if 语句中的条件一样简单吗? IE。首先只检查if (item != null),然后有一个嵌套的if 来检查对象是否存在的其他条件。
  • @ImaginaryHuman072889 不幸的是,拆分 if 语句并没有改变任何东西 - 仍然是同样的错误

标签: c# excel ssis nullreferenceexception


【解决方案1】:

你的逻辑似乎有错误:

if (item != null && (item.Value2 != null || item.Value2 != "" || item.Value2 != "NULL"))

假设我们有例如item.Value2 == null,那么条件item.Value2 != ""返回true,它会进入if-block,导致你描述的错误。

实际上我认为你应该只使用&amp;&amp; 而不要使用||

if (item != null && item.Value2 != null && item.Value2 != "" && item.Value2 != "NULL")

【讨论】:

  • 哈!真的就这么简单——我设法用我发布的方法克服了,但这确实是我需要的。我不敢相信我错过了如此微不足道的事情。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多