Avatar of trevor1940
trevor1940
 asked on

C#: How to deal with empty cells while reading excel spreadsheet

Hi I'm trying to read an excel spreadsheet I thought I cracked it until hitting empty cells

Ho do I stop this from erroring?

Error

Error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot perform runtime binding on a null reference
   at CallSite.Target(Closure , CallSite , Object )
   at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
   at CallSite.Target(Closure , CallSite , Object )
   at .Program.Main(String[] args) in \Program.cs:line 109

Open in new window



            string WorkBook = @"C:\Temp\MyFile.xls";
            if (File.Exists(WorkBook))
            {
                Excel.Application xlApp = new Excel.Application();



                Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(WorkBook);
                Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[3];
                Excel.Range xlRange = xlWorksheet.UsedRange;

                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;
                int PrefCount = 1;
                //iterate over the rows and columns and print to the console as it appears in the file
                //excel is not zero based!!
                for (int i = 3; i <= rowCount; i++)
                {
//. ...
                    string StrDescription = "";
                    try
                    {
                        if (xlRange.Cells[i, 2].Value2.ToString() != null || xlRange.Cells !=null)
                        {
                        StrDescription = xlRange.Cells[i, 2].Value2.ToString();
                    StrDescription = Regex.Replace(StrDescription, @"\r\n?|\n", " ");

                        }
                        else
                        {
                            Console.WriteLine("Description is Null");
                        }
  
                    Console.WriteLine("1 Description: {0}", StrDescription);
                }
                    catch (Exception e)
                {
                    Console.WriteLine("Error {0}", e);
                    continue;
                }

Open in new window

.NET ProgrammingC#

Avatar of undefined
Last Comment
AndyAinscow

8/22/2022 - Mon
AndyAinscow

instead of
if (xlRange.Cells[i, 2].Value2.ToString() != null || xlRange.Cells !=null)

does this help?
if (xlRange.Cells !=null && xlRange.Cells[i, 2].Value2.ToString() != null)

note changing the order and replacing the OR with AND
trevor1940

ASKER
Hi


Nope It still give the same Error

as dose

 if (xlRange.Cells[i, 2].Value2.ToString() != "")

Always the same cell(s) There could by just white space in it
AndyAinscow

It is that line of code that errors ?
You shot of the error said line 109
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
AndyAinscow

if ( ! xlRange.Cells[i, 2].Value2.ToString().IsNullOrWhitespace())  

I think that is how it is spelt - also not the ! to negate
trevor1940

ASKER
Without the "try" block that the line that errors

I'm using the latest version of .NET framework but get

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message='string' does not contain a definition for 'IsNullOrWhitespace'
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>
AndyAinscow

Ahhh, different .net functions.  (Framework vs non Framework versions of .net)

Does this compile
if (xlRange.Cells[i, 2].Value2.ToString().Trim() != "")


Please confirm the run time exception is thrown on this line and not on another line of code
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ASKER CERTIFIED SOLUTION
Kyle Abrahams, PMP

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Ark

null (Nothing in VB) can not be convereting to string using .ToString() method. Check for null cell.Value and if not nul - use .ToString. I'm using folowing function (VB)
   Public Function CellValue(cell As Excel.Range, Optional skipMerged As Boolean = False) As String
        If skipMerged AndAlso cell.MergeCells Then Return ""
        Dim v = cell.Value
        If v Is Nothing Then Return ""
        Return v.ToString
    End Function

Open in new window

trevor1940

ASKER

Please confirm the run time exception is thrown on this line and not on another line of code

Yes it was that line

Kyle's suggestion worked not totally sure what the  difference is

Thank you both and Stay safe
AndyAinscow

Kyles worked because I made a silly mistake.  It is a static function of the string class which takes a variable as parameter, not a function the string variable uses.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck