Java inserts a picture into Excel
- Import Java.io.FileOutputStream;
- Import Java.io.File;
- Import Java.io.ByteArrayOutputStream;
- Import java.io.IOException;
- Import Java.awt.image.BufferedImage;
- Import javax.imageio.*;
- Import Org.apache.poi.hssf.usermodel.HSSFWorkbook;
- Import Org.apache.poi.hssf.usermodel.HSSFSheet;
- Import Org.apache.poi.hssf.usermodel.HSSFPatriarch;
- import Org.apache.poi.hssf.usermodel.HSSFClientAnchor;;
- Public class Testpoi {
- public static void Main (string[] args) {
- FileOutputStream fileout = null;
- BufferedImage bufferimg =null;
- BufferedImage BUFFERIMG1 = null;
- try{
- //First put the read in a bytearrayoutputstream in order to produce ByteArray
- Bytearrayoutputstream bytearrayout = new Bytearrayoutputstream ();
- Bytearrayoutputstream byteArrayOut1 = new Bytearrayoutputstream ();
- bufferimg = Imageio.read (new File ("d:/piechart.jpg"));
- BUFFERIMG1 = Imageio.read (new File ("d:/fruitbarchart.jpg"));
- Imageio.write (bufferimg,"jpg", bytearrayout);
- Imageio.write (BUFFERIMG1,"jpg", byteArrayOut1);
- //Create a workbook
- Hssfworkbook WB = new Hssfworkbook ();
- Hssfsheet Sheet1 = Wb.createsheet ("new sheet");
- //hssfrow row = Sheet1.createrow (2);
- Hssfpatriarch Patriarch = Sheet1.createdrawingpatriarch ();
- Hssfclientanchor anchor = New Hssfclientanchor (0,0,,255, (short) 1,1, (short) ,20);
- Hssfclientanchor Anchor1 = new Hssfclientanchor (0,0,,255, (short) 2, ),60);
- Anchor1.setanchortype (2);
- //Insert Picture
- Patriarch.createpicture (anchor, Wb.addpicture (Bytearrayout.tobytearray (), hssfworkbook.picture_type_jpeg));
- Patriarch.createpicture (Anchor1, Wb.addpicture (Bytearrayout1.tobytearray (), hssfworkbook.picture_type_jpeg));
- Fileout = new FileOutputStream ("D:/workbook.xls");
- //write to Excel file
- Wb.write (fileout);
- Fileout.close ();
- }catch (IOException io) {
- Io.printstacktrace ();
- System.out.println ("io Erorr:" + io.getmessage ());
- } finally
- {
- if (fileout! = null)
- {
- try {
- Fileout.close ();
- }
- catch (IOException e)
- {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- }
- }
- }
Java inserts a picture into Excel