3

My excel sheet contains different regions on the same sheet like:

region1:                region2:       
John       2            A         1  
John       1            B         2  
Sue        1            C         3  
Sue        2            D         4  
Alice      5            E         5  
Bob        1            F         6  

I want to add new items into one of these regions without affecting the other regions. I tried using rowShift() method but it is also deleting the complete rows. Is there any way that can shift the specific cells down and can insert rows into the specific regions like this: In my given example I want to add one more row in region1 (also retaining all old rows) and it will become:

region1:                region2:       
newval     newval       A         1  
John       2            B         2  
John       1            C         3  
Sue        1            D         4  
Sue        2            E         5  
Alice      5            F         6
Bob        1
4
  • The example you've shown is only replacing cells John 2 with newval newval, it does not shift anything down. is that what you want?
    – JoseK
    Sep 7, 2010 at 11:34
  • By mistake i could not write the full rows. Please read the line (also retaining all old values). I do not need to replace , want to add.
    – chahal
    Sep 7, 2010 at 11:44
  • is there no one has any idea :(
    – chahal
    Sep 8, 2010 at 6:29
  • probably you have to shift down the row and then duplicate the cells you want
    – JoseK
    Sep 8, 2010 at 11:10

1 Answer 1

3

If the above issue still persisting, I can give you a method for the same.

public static void shiftCells(int startCellNo, int endCellNo, int shiftRowsBy, Sheet sheet){

    int lastRowNum = sheet.getLastRowNum();
    System.out.println(lastRowNum); //=7
    //      int rowNumAfterAdding = lastRowNum+shiftRowsBy;
    for(int rowNum=lastRowNum;rowNum>0;rowNum--){
        Row rowNew;
        if(sheet.getRow((int)rowNum+shiftRowsBy)==null){
            rowNew = sheet.createRow((int)rowNum+shiftRowsBy);
        }
        rowNew = sheet.getRow((int)rowNum+shiftRowsBy);
        Row rowOld = sheet.getRow(rowNum);
        System.out.println("RowNew is "+rowNum+" and Row Old is "+(int)(rowNum+shiftRowsBy));
        System.out.println("startCellNo = "+startCellNo+" endCellNo = "+endCellNo+" shiftRowBy = "+shiftRowsBy);
        for(int cellNo=startCellNo; cellNo<=endCellNo;cellNo++){
            rowNew.createCell(cellNo).setCellValue(rowOld.getCell(cellNo).getStringCellValue().toString());
            rowOld.getCell(cellNo).setCellValue("");
            System.out.println("working on " +cellNo);
        }
    }       
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.