How to move images in an excel sheet with java

☆樱花仙子☆ 提交于 2019-12-25 02:48:21

问题


I have an XSSFSheet with images at the end of my used rows. When adding a new row, I would like to shift all images one row down. I have found this similar question about moving charts, and have tried to use the part of the answer that does the actual moving of the charts, because It looked like it would work for images as well.

java.util.List<CTTwoCellAnchor> drawingAnchors = ((XSSFDrawing)sheet.getDrawingPatriarch()).getCTDrawing().getTwoCellAnchorList();
for (CTTwoCellAnchor drawingAnchor : drawingAnchors) {
    int fromRow = drawingAnchor.getFrom().getRow();
    int toRow = drawingAnchor.getTo().getRow();
    if (fromRow >= startRow) {
        drawingAnchor.getFrom().setRow(fromRow + n);
        drawingAnchor.getTo().setRow(toRow + n);
    }
}

but this did not work but throws a NoClassDefFoundError instead.
(Edit: I now found out that this error can be solved by providing the full jar of all of the schemas ooxml-schemas as mentioned in FAQ-N10025. thanks @Axel Richter)

After trying out several different approaches, I found a way to do it. Since it took me so long, and there is no info about this anywhere yet, I decided to post my findings here on SO.
Please find my solution in my own answer. Cheers


回答1:


The following code gets the Drawing Patriarch of the sheet, iterates over all it's shapes, and if the shape is of type XSSFPicture it modifies the rowindexes through its XSSFClientAnchor.

int moveRowsBy = 1; // 1 will move the images 1 row down. moveRowsBy can be negative to move up

XSSFDrawing drawing = sheet.getDrawingPatriarch();
for (XSSFShape shape : drawing.getShapes()) {
    if (shape instanceof XSSFPicture){
        XSSFClientAnchor anchor = ((XSSFPicture)shape).getClientAnchor();

        anchor.setRow1(anchor.getRow1() +moveRowsBy); 
        anchor.setRow2(anchor.getRow2() +moveRowsBy);

        // if needed you could change column too, using one of these:
        // anchor.setCol1(newColumnInt)
        // anchor.setCol1(anchor.getCol1() + moveColsBy)
    }
}


来源:https://stackoverflow.com/questions/54767890/how-to-move-images-in-an-excel-sheet-with-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!