2012-04-08 75 views
3

我遇到了将图片插入带有Apache POI(版本3.7)的Excel工作簿的问题。这里是我的代码:Apache POI“addPicture”方法不适用于我

private static void createAndFillWorkbook() { 
    FileOutputStream out = null; 
    FileInputStream in = null; 
    try { 
     HSSFWorkbook workbook = new HSSFWorkbook(); 
     File picture = new File("D:\\pngPict.png"); 
     byte[] buf = new byte[(int) picture.length()]; 
     in = new FileInputStream(picture); 
     in.read(buf); 
     workbook.addPicture(buf, Workbook.PICTURE_TYPE_PNG); 
     out = new FileOutputStream("D:\\Book3.xls"); 
     workbook.write(out); 
    } catch (Exception e) { 
    } finally { 
     try { 
      if (out != null) { 
       out.close(); 
      } 
      if (in != null) { 
       in.close(); 
      } 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 
} 

它不工作(我使用的是.xls文件格式),我不知道为什么。

回答

4

主要问题是Apache poi addPicture api取决于apache常用编解码器。从此位置下载jar commons-codec-1.6http://commons.apache.org/codec/download_codec.cgi并将该jar放入您的类路径中。

它应该工作。也可以尝试添加图片的样品示例到Excel

http://poi.apache.org/spreadsheet/quick-guide.html#Images

这里也

样本工作代码

http://www.codemiles.com/java/image-insert-in-excel-file-using-poi-t1340.html

希望这有助于!

+0

谢谢!我稍后再试,并回答结果。 – VladislavLysov 2012-04-08 15:37:17

+0

我有同样的问题...正如你所说,我尝试添加jar。但仍然无法添加图片,我也没有得到任何例外。什么可能是实际问题? – Stunner 2013-10-29 06:25:19

+0

@Stunner将jar添加到您的构建路径中,然后尝试使用它。 :)对不起,延迟回复 – 2014-04-02 11:39:30