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 :
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();
}
}
}

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: Drawing a Shape in Excel Sheet
Post your Comment