【发布时间】:2019-09-25 03:44:56
【问题描述】:
我正在尝试从 Excel 工作表中读取单元格值,并使用 Value 和 Value2 来查看单元格值。它不断抛出“System.NullReferenceException:'对象引用未设置为对象的实例。'”错误。我无法弄清楚代码中的问题出在哪里。
我知道文件路径和它正在读取的 Excel 工作表是正确的。
public String readEDriver()
{
int nRows = 1;
int nCols = 1;
String driverLoc = null;
Excel.Application excelApp = new Excel.Application();
if (excelApp != null)
{
Workbook excelWorkbook;
excelWorkbook = excelApp.Workbooks.Open("C:\\A\\Config.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Worksheet excelWorksheet;
excelWorksheet = (Excel.Worksheet)excelWorkbook.Worksheets[1];
excelWorksheet.Activate();
String eName =excelWorksheet.Name;
if (excelWorksheet == null)
{
throw new Exception(string.Format("Named worksheet ({0}) not found.", excelWorksheet));
}
else
{
var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
if (excelWorksheet.Cells[nRows,nCols]!=null)
{
cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
driverLoc = cellVal.ToString();
}
}
excelWorkbook.Close();
excelApp.Quit();
}
return driverLoc;
}
它打破了
var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2;
无法检索 Excel 范围并给出 NullReferenceException
留言:
System.NullReferenceException:对象引用未设置为对象的实例。
堆栈跟踪:
【问题讨论】:
-
你在哪一行得到错误?
-
糟糕,我将更新我的 Q,我确实放置了面包点,它在 var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]) 处中断。值2; ..它无法检索 Excel 范围并给出 NullReferenceException
-
改变其他条件为
else { if (excelWorksheet.Cells[nRows,nCols]!=null) { var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols]).Value2; driverLoc = cellVal.ToString(); } } -
@Matt.G 这没什么区别......即使对于 var cellVal = ((Microsoft.Office.Interop.Excel.Range)excelWorksheet.Cells[nRows, nCols] 也会失败).Value2 无论是在内部还是外部条件都无关紧要。
-
试试
(string)((excelWorksheet.Cells[nRows, nCols] as Excel.Range)?.Value2)