System.NullReferenceException 在 Excel C# 中循环遍历空值时
本文关键字:循环 遍历 空值 NullReferenceException Excel System | 更新日期: 2023-09-27 18:32:13
我遇到了一个小问题,关于从Excel文件中提取数据,忽略我删除一些东西的第一部分,这是因为正在检索的文件是24列,目标文件大约是12列,所以我正在删除一些列。
长话短说,我试图匹配的部分,如果任何行中第 5 列的值是"x",然后在同一行的第二列中写例如"E"......否则,检查"X"是否在第 6 列中,则表示"P"应该在该行的第二列中,依此类推......
问题是对于每个单元格,它要么是值"x",要么是空的。(excel文件中没有值),所以每当代码循环遍历空元素时似乎都会出现问题,它会抛出此错误
l = new Microsoft.Office.Interop.Excel.Application();
xl.Visible = false;
Microsoft.Office.Interop.Excel.Workbook workbook = xl.Workbooks.Open(p_sUBKPath, Type.Missing, Type.Missing, 4, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
Microsoft.Office.Interop.Excel.Range range = ws.UsedRange;
// delete columns that we don't need from the new excel file
Microsoft.Office.Interop.Excel.Range range2 = ws.get_Range("A1","A1");
range2.EntireColumn.Delete();
Microsoft.Office.Interop.Excel.Range range3 = ws.get_Range("B1", "B1");
range3.EntireColumn.Delete();
Microsoft.Office.Interop.Excel.Range range4 = ws.get_Range("D1", "L1");
range4.EntireColumn.Delete();
Microsoft.Office.Interop.Excel.Range range5 = ws.get_Range("I1", "M1");
range5.EntireColumn.Delete();
Microsoft.Office.Interop.Excel.Range range6 = ws.get_Range("K1", "K1");
range6.EntireColumn.Delete();
//insert a new column ( Category)
Microsoft.Office.Interop.Excel.Range range7 = ws.get_Range("B1", "B1");
range7.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight);
object[,] values = (object[,])range.Value2;
values[1, 2] = (string)"Cat.";
for (int row = 2; row <= values.GetUpperBound(0); row++)
{
try
{
if ((!String.IsNullOrEmpty(values[row, 5].ToString())) && values[row, 5].ToString() == "x")
{
values[row, 2] = (string)"E";
}
else if ((!String.IsNullOrEmpty(values[row, 6].ToString())) && values[row, 6].ToString() == "x")
{
values[row, 2] = (string)"P";
}
else if ((!String.IsNullOrEmpty(values[row, 7].ToString())) && values[row, 7].ToString() == "x")
{
values[row, 2] = (string)"Phy";
}
else if ((!String.IsNullOrEmpty(values[row, 8].ToString())) && values[row, 8].ToString() == "x")
{
values[row, 2] = (string)"L";
}
else if ((!String.IsNullOrEmpty(values[row, 9].ToString())) && values[row, 9].ToString() == "x")
{
values[row, 2] = (string)"Ex";
}
else
MessageBox.Show("unknow");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
错误是:
System.Null引用异常对象引用未设置为对象的实例
我会在执行 .tostring() 之前进行空检查。 即:
(!String.IsNullOrEmpty(values[row, 5].ToString()))
自
!(values[row, 5] == null) && (!String.IsNullOrEmpty(values[row, 5].ToString()))