Search code examples
c#excelparsingexceptiondocuments

C Sharp ExcelParser throws exceptions on empty cells


So, im trying to make an Excel documents parser, and everything goes fine, until it hits empty cell in Excel. Then it throws an exception *"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" occured in System.Core.dll"

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();
        }
    }
}

Solution

  • I guess that cell.Value2 is null for an empty cell. In that case you can't call .ToString() on it.

    You can however check for it:

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