我在使用Apache POI(版本3.7)将图片插入Excel工作簿时遇到问题。这是我的代码:
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文件格式),我不确定原因。
答案 0 :(得分:4)
主要问题是Apache poi addPicture
api取决于apache常用编解码器。从此位置http://commons.apache.org/codec/download_codec.cgi下载jar commons-codec-1.6
并将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
希望这会有所帮助!!