Jexcel

Java Excel API Projects

Java Excel API Project 1

how to add an image in an excel sheet using jexcel
Previous Home Next

 

In this example we are going to add an image to an excel sheet using the JExcel Api. This example will give the way to add any image to your excel sheet.

To add an image to your excel sheet firstly you have to import the jxl.write.WritableImage class. This class contains the methods which are used for adding the image on your workbook.
 In this example we have created an WritableImage object, in the constructor of the WritableImage we have passed few parameters viz.
WritableImage(double x, double y, double width, double height, File image)
where , double x -> is the position of the column
            double y -> is the position of the row
            double height -> is the height of the image
           double width -> is the width of the image
           File image-> the file containing the desired image to be added on the workbook.

Then we have used the add(WritableImage wi) method on the sheet to add the image.

In the following we will see, how can we add an image to the worksheet of an workbook.

 

package r4r.co.in;

import java.io.IOException;
import java.io.File;
import jxl.Workbook;
import jxl.write.WritableCellFormat;
import jxl.Image;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.Label;
import jxl.format.*;
public class InsertImageInWorkbook {

/**
* @param args
*/
public static void main(String[] args) throws IOException, WriteException{
// TODO Auto-generated method stub

try
{
WritableWorkbook workbook=Workbook.createWorkbook(new File("F:/JAVA PROJECTS/Jexcel/src/r4r/co/in/firstsheet.xls"));
WritableSheet sheet=workbook.createSheet("mysheet", 0);
WritableFont wfobj=new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD);
WritableCellFormat cfobj=new WritableCellFormat(wfobj);
cfobj.setBackground(Colour.PINK);

cfobj.setWrap(true);

Label lblImage=new Label(1,0,"Image", cfobj);

sheet.addCell(lblImage);
WritableImage imgobj=
new WritableImage(5, 7, 9, 11, new File("F:/JAVA PROJECTS/Jexcel/Sunset.png")); sheet.addImage(imgobj); workbook.write(); workbook.close(); } catch(IOException e) { e.printStackTrace(); } catch(WriteException e) { e.printStackTrace(); } } }

Previous Home Next