如何使用Java在Excel工作表中移动图像 [英] How to move images in an excel sheet with java

查看:122
本文介绍了如何使用Java在Excel工作表中移动图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XSSFSheet,在我使用的行的末尾有图像.添加新行时,我想将所有图像向下移动一行.我发现了关于移动图表的类似问题,并尝试使用答案的一部分来进行实际的移动.图表,因为它看起来也适用于图像.

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);
    }
}

,但是这不起作用,而是抛出了NoClassDefFoundError.
(我现在发现可以通过提供

but this did not work but throws a NoClassDefFoundError instead.
( 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)

尝试了几种不同的方法之后,我找到了一种方法.由于花了我很长时间,而且到目前为止还没有任何相关信息,所以我决定将自己的发现发布在SO上.
请在我自己的答案中找到我的解决方案.干杯

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

推荐答案

以下代码获取工作表的绘图父级,遍历其所有形状,如果形状为XSSFPicture类型,它将通过XSSFClientAnchor.

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)
    }
}

这篇关于如何使用Java在Excel工作表中移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆