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

查看:57
本文介绍了如何使用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.
(我现在发现可以通过提供 ooxml-schemas 中提到的所有模式的完整 jar 来解决此错误:https://poi.apache.org/help/faq.html#faq-N10025" rel="nofollow noreferrer">FAQ-N10025.谢谢@Axel Richter)

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天全站免登陆