C Sharp ExcelParser在空单元格抛出exception

所以,即时尝试使Excel文档分析器,一切顺利,直到它击中Excel中的空单元格。 然后在System.Core.dll中引发exception*“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”

namespace ExcelParser { class Program { static void Main(string[] args) { Excel.Application excelApp = new Excel.Application(); excelApp.Visible = true; string _sourceFile = "F:\\Bullshit\\book1.xlsm"; excelApp.Workbooks.Open(_sourceFile); int row = 1; Excel.Worksheet currentSheet = (Excel.Worksheet)excelApp.Workbooks[1].Worksheets[1]; Console.WriteLine("Initializing"); while (currentSheet.get_Range("A" + row).Value2 != null) { List<string> tempList = new List<string>(); for (char column = 'A'; column < 'J'; column++) { Console.Write(column + row.ToString()); Excel.Range cell = currentSheet.get_Range(column + row.ToString()); Console.WriteLine(cell.Value2.ToString() != "" ? cell.Value2.ToString() : "null!"); // the problem line } row++; } Console.ReadKey(); } } } 

我猜这个cell.Value2为空的单元格为空。 在这种情况下,你不能调用它的.ToString()。

你可以检查它:

 Console.WriteLine(cell.Value2 != null ? cell.Value2.ToString() : "null!"); 

如果没有对象,则不能转换对象的ToString方法。 它会返回null,但null不是一样的""尝试使用这一行:

Console.WriteLine(("" + cell.Value2).ToString() != "" ? cell.Value2.ToString() : "null!");

一个快速和肮脏的方式来摆脱例外只是

 try { Console.WriteLine(cell.Value2.ToString() != "" ? cell.Value2.ToString(): "null!"); } catch(exception e) { Console.WriteLine(e.Argument); }