2014-02-24 86 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