我发现了许多与此类似的问题,但没有一个能解决我的问题。我正在使用 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
ect?
你的逻辑似乎有错误:
if (item != null && (item.Value2 != null || item.Value2 != "" || item.Value2 != "NULL"))
假设我们有例如item.Value2 == null
,则条件item.Value2 != ""
返回true
,它将进入 if 块,导致您所描述的错误。
事实上,我认为您应该只使用&&
而不使用||
:
if (item != null && item.Value2 != null && item.Value2 != "" && item.Value2 != "NULL")