2014-02-24 85 views
11

我在插入一張圖片在Excel表單im製作中遇到麻煩。 關於這個問題有很多問題,但我根本無法弄清楚我做錯了什麼。我 代碼運行,顯示沒有錯誤,但我沒有看到的圖像插入:(Apache POI插入圖像

這裏是代碼:

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

POI已經有了問題插入Word文檔中的圖片,所以我會認爲這是相關的。 – dkatzel

+1

它在新表上工作嗎? POI只能將圖像添加到沒有任何現有圖像的圖紙上,如果您嘗試將圖像添加到已有一些圖像的圖紙上,它將不起作用 – Gagravarr

回答

14

的問題是,你的主播不正確 您需要設置的所有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(); 
+0

嗨!我需要不從磁盤插入圖像。我的圖像存儲在位圖陣列的內存中,我不想將它保存在硬盤上。我可以將位圖數組中的數據直接插入.docx文件嗎? –

+0

對不起,從來沒有與docx工作。但爲什麼不呢? AFAIK poi需要inputstreams,你可以使用bytearrayinputStrean – Mirco