Search code examples
c#excelstringindexoutofbounds

Get Data From Excel - Index exceeds bounds


I am trying to get data from an Excel file. I know that indexing in excel starts from 1, but still when reading a simple matrix, I am getting an Index exceeds bounds error.
Here is a simple method I'm using:

public static string[,] ReadFromExcel(Worksheet excelSheet)
{
    if (excelSheet == null) return new string[1,1];

    Microsoft.Office.Interop.Excel.Range xlRange = excelSheet.UsedRange;
    int firstRow = xlRange.Row;
    int firstColumn = xlRange.Column;

    int lastRow = xlRange.Row + xlRange.Rows.Count - 1;
    int lastColumn = xlRange.Column + xlRange.Columns.Count - 1;

    string[,] data = new string[xlRange.Rows.Count - xlRange.Row, xlRange.Columns.Count - xlRange.Column];
    for (int i= 0; i<= lastRow - firstRow; i++)
    {
        for (int j= 0; j <= lastColumn - firstColumn; j++)
        {
            data[i,j] = (string)(excelSheet.Cells[firstRow + i][firstColumn + j] as Range).Value;
            //When I try to read values I get an error
            System.Windows.MessageBox.Show(data[i, j]);
        }
    }

    return data;
}

What am I missing?


Solution

  • The size of your "data" array should match the number of rows & columns:

      string[,] data = new string[xlRange.Rows.Count, xlRange.Columns.Count];
    

    Although the start index for Excel Interop is 1, rather than zero, the count is correct & you don't need to subtract the start row & column.