1

I'm trying to return the cell value from an excel file and I am able to receive the value but right after returning the value it gives me a System.ArgumentOutOfRangeException. It's confusing since the program was able to receive the data and show me in a Windows Forms Message Box but it still gives me the error that I went out of range.

public static void RemoveUpdates()
        {
            //Grabs data from excel file by given file path
            IWorkbook wb = new XSSFWorkbook("INSERT FILE PATH HERE");
            ISheet ws = wb.GetSheetAt(0);
            
            //iterates through each row of the excel file
            for (int x = 1; x <= ws.LastRowNum; x++)
            {
                IRow row = ws.GetRow(x);
                
                //Opens a windows forms message box to present the data received from the cell
                MessageBox.Show(row.Cells[6].ToString());
            }
        }

Error: System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index'

Any help would be appreciated

zaid iqbal
  • 101
  • 1
  • 2
  • 11
  • 1
    Are you *really* sure that row.Cells[6] exists? – Hans Kesting Jul 20 '20 at 20:24
  • 1
    C# lists / arrays are 0 indexed – Jawad Jul 20 '20 at 20:27
  • your loop probably goes too far. maybe try `for (int x = 0; x <= ws.LastRowNum-1; x++)`? The error is referring to the `ws.GetRow(x)` once x has gotten bigger than the row count of ws, not the `row.Cells[6].ToString()` – ArcherBird Jul 20 '20 at 20:34
  • 1
    `for (int x = 0; x < ws.LastRowNum; x++)` – Rufus L Jul 20 '20 at 20:41
  • 1
    From the [documentation for `XSSFSheet.GetRow(int rownum)`](https://poi.apache.org/apidocs/dev/org/apache/poi/xssf/usermodel/XSSFSheet.html#getRow-int-): *Returns the logical row (**0-based**).* Your code assumes the collection is 1-based. You should fix that as suggested by other comments. Confirmation from the npoi sources for [`ISheet.GetRow(int rownum)`](https://github.com/tonyqus/npoi/blob/master/main/SS/UserModel/Sheet.cs#L108): *row to get (**0-based**).* – dbc Jul 20 '20 at 22:22

0 Answers0