Java Apache POI 插入图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21991473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:53:44  来源:igfitidea点击:

Apache POI insert image

javaandroidimageexcelapache-poi

提问by SteBra

I am having troubles with inserting a picture in an excel sheet im making. There are a lot of question about this subject, but I simply cannot figure out what am I doing wrong. My code runs, shows no errors but I do not see an image inserted :(

我在我制作的 Excel 表格中插入图片时遇到问题。关于这个主题有很多问题,但我根本无法弄清楚我做错了什么。我的代码运行,没有显示错误,但我没有看到插入的图像:(

here is the code:

这是代码:

    InputStream is = new FileInputStream("nasuto_tlo.png");
    byte [] bytes = IOUtils.toByteArray(is); 
    int pictureIndex = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
    is.close();

    CreationHelper helper = wb.getCreationHelper();
    Drawing drawingPatriarch = sheet.createDrawingPatriarch();
    ClientAnchor anchor = helper.createClientAnchor();

    anchor.setCol1(2);
    anchor.setRow1(3);
    Picture pict = drawingPatriarch.createPicture(anchor, pictureIndex);
    pict.resize();

    try {
        FileOutputStream out = new FileOutputStream(root+"/Busotina/Busotina1.xls");
        wb.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

采纳答案by Mirco

the problem is that your anchor is not correct. You need to set all 4 values, because the default ones are 0 - but your first column can not be more right than your second one ;) You'll get negative extent. You should get a warning when you open the excel file that it is corrupt.

问题是你的锚不正确。您需要设置所有 4 个值,因为默认值为 0 - 但您的第一列不能比第二列更正确 ;) 您将得到负值。当您打开 Excel 文件时,您应该会收到一条警告,指出它已损坏。

So try

所以试试

anchor.setCol1(2);
anchor.setCol2(3);
anchor.setRow1(3);
anchor.setRow2(4);


A working example from some code I wrote:

我写的一些代码的一个工作示例:

// read the image to the stream
final FileInputStream stream =
        new FileInputStream( imagePath );
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();

final ClientAnchor anchor = helper.createClientAnchor();
anchor.setAnchorType( ClientAnchor.MOVE_AND_RESIZE );


final int pictureIndex =
        workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_PNG);


anchor.setCol1( 0 );
anchor.setRow1( LOGO_ROW ); // same row is okay
anchor.setRow2( LOGO_ROW );
anchor.setCol2( 1 );
final Picture pict = drawing.createPicture( anchor, pictureIndex );
pict.resize();