2

I am using the following code to read values from an Excel spreadsheet:

// Start with passed
int lastPassRow = sheets[passedVehicles].GetLength(0);

for (int i = 1; i < lastPassRow; i++)
{
   // Exception here
   if(DateTime.TryParse(sheets[passedVehicles][i, 0].ToString(), out result))
   {
      passedDates.Add((DateTime)sheets[passedVehicles][i, 0]);
   }
}

The type of sheets[passedVehicles] is a multidimensional array of Object[,] and the for loop above is giving me an IndexOutOfRange exception at i = 1, despite that I check the number of rows.

I added some logging for the spreadsheet in question, and have verified:

  • i = 1 is the iteration that is failing
  • The value of lastPassRow is 4
  • The value of sheets[passedVehicles].GetLength(1) is also four.

All values appear to be in range to me. Is there something else that could cause this exception?

Note: I am starting at i = 1 because row 0 is a header in the spreadsheet and does not contain data I am trying to read.

4
  • Shouldn't this be sheets[passedVehicles][0, i]? Commented May 19, 2015 at 13:50
  • @Kryptos No, I've always used the [row, column] convention and it has worked for everything except this. Commented May 19, 2015 at 13:51
  • 2
    What if you evaluate sheets[passedVehicles].GetLowerBound(0) and the same for 1? Excel arrays are 1-based, not 0-based, so it could have a lower bound of 1 rather than 0. C# arrays are always 0-based, but the more generic Array class actually allows for arbitrary lower and upper bounds. Commented May 19, 2015 at 13:55
  • Ok then try sheets[passedVehicles][i, 1] Commented May 19, 2015 at 13:57

1 Answer 1

4

I suspect it's the 0 that's out of range.

Excel arrays are 1-based, not 0-based as you might expect.

Sign up to request clarification or add additional context in comments.

1 Comment

You're absolutely right. No more exception! I didn't read the right data, I suspect because of an error in my LINQ statement. I'm gonna try and verify that it's a separate issue, and as long as that's the case I'll come back and accept this. Great catch!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.