Home Tutorials Poi Drawing a Shape in Excel Sheet
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

Drawing a Shape in Excel Sheet

Advertisement
In this section, you will learn how to draw a shape in excel sheets using Apache POI library.

Drawing a Shape in Excel Sheet

In this section, you will learn how to draw a shape in excel sheets using Apache POI library.

Using Apache POI, you can draw a shape with the help of Microsoft Office drawing tools. The top-most shape is the patriarch. This is not visible on the sheet at all. To start drawing you need to call createPatriarch on the HSSFSheet class.

You need to follow the following step to create a shape :

  • First, create a patriarch 

  • Secondly, for positioning the shape on the excel sheet , create an anchor.

  • Use patriarch to create a shape.

  • Set the shape type (line, oval, rectangle etc...)

  • Set any other style details describing the shape. (eg: line thickness, etc...)

EXAMPLE

In the given below example, we are going to create a oval shape :

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFShape;
import org.apache.poi.hssf.usermodel.HSSFSimpleShape;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class XLDrawingShape {
public static void main(String args[]) throws FileNotFoundException{
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet("Data Validation");
HSSFPatriarch patriarch = (HSSFPatriarch) sheet.createDrawingPatriarch();
HSSFClientAnchor a = new HSSFClientAnchor( 0, 0, 1023, 255, (short) 1, 0, (short) 2, 1 );
HSSFSimpleShape shape1 = patriarch.createSimpleShape(a);
shape1.setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL);
shape1.setLineStyleColor(10,10,10);
shape1.setFillColor(90,10,200);
shape1.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3);
shape1.setLineStyle(HSSFShape.LINESTYLE_DOTSYS);
FileOutputStream fileOut = new FileOutputStream("xls/XLDrawingShape.xls");
try {
workbook.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

OUTPUT

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 24, 2011

Related Tutorials

Ask Questions?    Discuss: Drawing a Shape in Excel Sheet  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com