簡體   English   中英

Apache POI插入圖像

[英]Apache POI insert image

我在制作excel表中插入圖片時遇到了麻煩。 關於這個問題有很多問題,但我根本無法弄清楚我做錯了什么。 我的代碼運行,顯示沒有錯誤,但我沒有看到插入的圖像:(

這是代碼:

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

問題是你的錨不正確。 您需要設置所有4個值,因為默認值為0 - 但是您的第一列不能比第二列更正確;)您將獲得負面范圍。 當您打開Excel文件已損壞時,您應該收到警告。

所以試試吧

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

我寫的一些代碼的工作示例:

// 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM