问题
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.
回答1:
I suspect it's the 0
that's out of range.
Excel arrays are 1-based, not 0-based as you might expect.
来源:https://stackoverflow.com/questions/30327476/indexoutofrangeexception-on-multidimensional-array-despite-using-getlength-check