Search code examples
javaapacheapache-poixlsx

poi shiftRows resizes and does not move images


I'm using POI and i want to insert some lines in a xlsx. In this file, I have some images inside a table. When i shift rows by doing this :

sheet.shiftRows(30, sheet.getLastRowNum(), 10, true, true);

some images are in the wrong place and are resized.

How can I move all the items at once without resizing images and let them in the right place?


Solution

  • Came across this issue and this code worked for me Basically what needs to happen is change the anchors for the images to reflect the new row indexes.

    XSSFDrawing drawings = mainSheet.createDrawingPatriarch();
    for(XSSFShape shape : drawings.getShapes()){
        if(shape instanceof Picture){
            XSSFPicture picture = (XSSFPicture) shape;
            XSSFClientAnchor anchor = picture.getClientAnchor();
            int row1 = anchor.getRow1();
            if (row1 >= 30 && row1 <= mainSheet.getLastRowNum()) {
                int row2 = anchor.getRow2();
                anchor.setRow1(row1 + 10);
                anchor.setRow2(row2 + 10);
            }
         }
     }
    

    This is what happens :

    • Get all the drawings in the current sheet.
    • Check if the image row1 anchor is within the range of rows being shifted
    • Set the new row1 anchor to be the old row1 anchor + the number of rows being shifted
    • Set the new row2 anchor to be the old row1 anchor + the number of rows being shifted