java导出图片到excel_POI:将图片导出到Excel

POI什么的在此我就不多作介绍了,在POI中生成图片有关的有HSSFPatriarch和HSSFClientAnchor,前者负责在表中创建图片,后者负责设置图片的大小位置。

/**

* 根据输出路径及要导出的图片文件生成EXCEL

* @param desPath

* @param file

*/

private void createSheet(String desPath, String file) {

try {

// 创建图片页

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet sheet = workbook.createSheet("模型图");

ByteArrayOutputStream outStream = new ByteArrayOutputStream();

// 将图片写入流中

BufferedImage bufferImg = ImageIO.read(new File(file));

ImageIO.write(bufferImg, "PNG", outStream);

// 利用HSSFPatriarch将图片写入EXCEL

HSSFPatriarch patri = sheet.createDrawingPatriarch();

HSSFClientAnchor anchor = new HSSFClientAnchor(5, 5, 5, 5,

(short) 5, 2, (short) 15, 25);

patri.createPicture(anchor, workbook.addPicture(

outStream.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

workbook.write(new FileOutputStream(desPath));

} catch (Exception e) {

final String message = e.toString();

Display.getDefault().syncExec(new Runnable() {

@Override

public void run() {

MessageBox box = new MessageBox(Display.getDefault().getActiveShell(), SWT.ERROR);

box.setText("导出错误");

box.setMessage(message);

box.open();

}

});

e.printStackTrace();

}

}

你可能感兴趣的:(java导出图片到excel)