-1

I'm writing a code that finds the desired column in an input sheet and takes the entire column and put it in a different order in an output sheet. Basically I want to take in an Excel file and reorganize it in an output file. The path I've chosen is to find the numerical value of the column and use that to find the cells within each row. I'm getting an error at the line rdrCell = inputSheet.getRow(placeRow+1).getCell(y); is there something wrong with the way I'm trying to get the cell value?

for(Iterator<Cell> cit = idRow.cellIterator(); cit.hasNext(); )
            {
                Cell cell = cit.next();
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String chr = "Chr";
                Row rdrRow = null;
                Cell rdrCell = null;
                if(chr.equals(cell.getStringCellValue()))
                {
                    int y = cell.getColumnIndex();
                    for(int placeRow = 0; placeRow<=rowCounter;placeRow++)
                    {
                        // error in line below
                        rdrCell = inputSheet.getRow(placeRow+1).getCell(y);
                        rdrCell.setCellType(Cell.CELL_TYPE_STRING);
                        String chrString = rdrCell.getStringCellValue();
                        Cell chrCell = outputSheet.createRow(placeRow).createCell(0);
                        chrCell.setCellValue(chrString);
                    }

                }
dxdy
  • 540
  • 2
  • 13
UberKoolMan
  • 145
  • 1
  • 2
  • 8

2 Answers2

2

Your for loop goes too far.

for(int placeRow = 0; placeRow<=rowCounter;placeRow++)

Change the middle part and check for placeRow < rowCounter instead of <=

WarrenFaith
  • 57,492
  • 25
  • 134
  • 150
  • After changing the less than sign it works, so thanks! However when I try to copy and paste the same code for another column, it seems like it removes the first column entirely. Why is that? – UberKoolMan Oct 01 '15 at 00:13
1

This is happening when your placeRow is equal the last index (i mean placeRow = rowCounter), so you are trying to get the placeRow + 1 but you already reached the rows limit and it does not exist.

I suggest you to remove this + 1 and just use:

rdrCell = inputSheet.getRow(placeRow).getCell(y);

So if you want to jump first line (like it`s happening), just start your iterator at index 1, like: int placeRow = 1

Túlio Castro
  • 1,313
  • 10
  • 17
  • 2
    why should I do a -1 each time for a check if I can just compare it with < instead of <=? Harder to read, more stuff to do, less effective. – WarrenFaith Sep 30 '15 at 21:05
  • Indeed, i agree with you.I read again and i found the real problem, im editing my answer. Thnks – Túlio Castro Sep 30 '15 at 21:12