Java Program to Draw a Shape in Excel Sheet using Apache POI
Last Updated :
17 Mar, 2022
Apache POI supports customized printing by allowing users to select a range of cells in order to configure the desired print area in a worksheet using Java Program. 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.
Let's take an example to Create an oval shape using all the styling to Excel File using Apache POI.
Approach:
- First, we need to add Maven Dependency to the maven project, we can include the POI dependency using the pom.xml file as shown below:
- Create an instance of the workbook
- Create a spreadsheet in the above workbook.
- Create rows using XSSFRow
- Create a cell using XSSFCell.
- Create a patriarch by using HSSFPatriarch.
- For positioning the shape on the excel sheet, create an anchor by using HSSFClientAnchor.
- Set the shape type (line, oval, rectangle, etc...)
- Set any other style details describing the shape. (eg: line thickness, etc...)
- Writing the content to the workbook by defining the object of type FileOutputStream
- Close the connection of the file.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
Methods Required
Method 1: HSSFClientAnchor()
- HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, short col1, int row1, short col2, int row2)
- Creates a new client anchor and sets the top-left and bottom-rightcoordinates of the anchor.
- Note: Microsoft Excel seems to sometimes disallow higher y1 than y2 or higher x1 than x2, Â you might need to reverse them and draw shapes vertically or horizontally flipped!
- Parameters:
- dx1 - the x coordinate within the first cell.
- dy1 - the y coordinate within the first cell.
- dx2 - the x coordinate within the second cell.
- dy2 - the y coordinate within the second cell.
- col1 - the column (0 based) of the first cell.
- row1 - the row (0 based) of the first cell.
- col2 - the column (0 based) of the second cell.
- row2 - the row (0 based) of the second cell.
Method 2: createSimpleShape()
- Creates a simple shape. This includes such shapes as lines, rectangles, and ovals.
- Parameters: anchor the client anchor describes how this group is attached to the sheet.
- Returns: the newly created shape.
Method 3: setShapeType(HSSFSimpleShape.OBJECT_TYPE_OVAL)
- Parameters: value - shapeType
Method 4: setLineStyleColor(8, 8, 8)
- The color is applied to the lines of this shape.
- Parameters: red green blue
Method 5: setFillColor(100, 10, 150)
- The color is used to fill this shape.
- Parameters: red green blue
Method 6: setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3)
- Sets the width of the line. 12700 = 1 pt.
- Parameters: lineWidth width in EMU's. 12700EMU's = 1 pt
Method 7: setLineStyle(HSSFShape.LINESTYLE_DOTSYS)
- Sets the line style.
- Parameters: lineStyle One of the constants in LINESTYLE_
Implementation:
Java
// Java Program to Creating an Oval Shape Using all the
// styling to Excel File using Apache POI
// Importing required classes
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;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
throws IOException
{
// Naming a workbook
String excelfilename = "GFG.xls";
// Creating a workbook
Workbook workbook = new HSSFWorkbook();
// Creating a spreadsheet by creating an object of
// XSSFSheet and also give name
Sheet spreadsheet
= workbook.createSheet("XLDrawingShape");
// Creating an object patriarch of HSSFPatriarch.
HSSFPatriarch patriarch
= (HSSFPatriarch)
spreadsheet.createDrawingPatriarch();
// Creating an object anchor of HSSFClientAnchor
// and also set a value
HSSFClientAnchor anchor = new HSSFClientAnchor(
0, 0, 1023, 255, (short)1, 0, (short)5, 4);
// Creating an object shape of HSSFSimpleShape
HSSFSimpleShape shape
= patriarch.createSimpleShape(anchor);
// Setting all the attributes of shape
shape.setShapeType(
HSSFSimpleShape.OBJECT_TYPE_OVAL);
shape.setLineStyleColor(8, 8, 8);
shape.setFillColor(100, 10, 150);
shape.setLineWidth(HSSFShape.LINEWIDTH_ONE_PT * 3);
shape.setLineStyle(HSSFShape.LINESTYLE_DOTSYS);
// try block to check for exceptions
try {
// Placing the output file in default location
// and also kept in try catch block
FileOutputStream outputfile
= new FileOutputStream(excelfilename);
// Writing to workbook
workbook.write(outputfile);
// Closing workbook using close() method
outputfile.close();
// Displaying message for console window when
// program is successfully executed
System.out.println(excelfilename
+ " is written successfully");
}
// Catch block to handle the exceptions
catch (FileNotFoundException e) {
// Displaying error message for console window
// when program is not successfully executed
System.out.println("ERROR!! " + e.getMessage());
}
}
}
Â
Â
Output: On console window
Â
When the program is successfully executed.
Â
GFG.xlsx is written successfully.
Â
When the program is not successfully executed.
Â
ERROR!! GFG.xlsx (The process cannot access the file because it is being used by another process)
Â
Output: Workbook(excel file)
Â
Â
Similar Reads
Java Program to Create blank Excel Sheet
ApachePOI stands for poor obfuscation Implementation which is a Java API for reading and writing Microsoft documents. It contains classes and interfaces namely Wordbook, Sheet, Row, and Cell. Apache POI can be used to access 'xlsx' extension files and as well as 'xlsx' extension files Concept: Apach
3 min read
Java Apache POI Programs - Basic to Advanced
This Java Apache POI program guide provides a variety of programs on Java POI, that are frequently asked in the technical round in various Software Engineering/core JAVA Developer Interviews. Additionally, All practice programs come with a detailed description, Java code, and output. Apache POI is a
3 min read
Java Applet | Draw a line using drawLine() method
This article shall be explaining the code to draw a line using paint in Java. This uses drawLine() method. Syntax: drawLine(int x1, int y1, int x2, int y2) Parameters: The drawLine method takes four arguments: x1 - It takes the first point's x coordinate. y1 - It takes first point's y coordinate. x2
2 min read
Java Program to Find out the Area and Perimeter of Rectangle using Class Concept
The perimeter is the length of the outline of a shape. To find the perimeter of a rectangle or square you have to add the lengths of all four sides. x is in this case the length of the rectangle while y is the width of the rectangle. The area is the measurement of the surface of a shape. The main ta
3 min read
Java Program to Find the Area of a Circle Given the Radius
A circle is a simple shape consisting of all the points in the plane that are equidistant from a point known as the center of the circle. In this article, we will learn how to find the area of the circle. Terminology: Area: A quantity that represents the extent of a 2-dimensional figure or shape in
2 min read
Java Program to Extract Content from a Excel sheet
Spreadsheets are the easier way to represent table like data and can give a visual representation of data in tabular format. In this article, let us see how to extract the contents of the Excel sheet via java. Here there arise two cases where Maven is considered in the program or not. Discussing bot
10 min read
How to Create Different Types of Cells in a Spreadsheet using Java?
Apache POI is an API which was provided by Apache Foundation and is used to set the various type of values to the cell. The overloading function setCellValue() of Apache POI is used to set the value type of the cell. Maven is a powerful project management tool that is based on POM (project object mo
4 min read
How to Apply Different Styles to a Cell in a Spreadsheet using Java?
Apache POI is a powerful API that enables the user to create, manipulate, and display various file formats based on Microsoft Office using java programs. Using POI, one should be able to perform create, modify, and display/read operations on the following file formats. For Example, Java doesnât prov
6 min read
How to Set the Print Area of a Spreadsheet Using Java?
We can set the print area in a Spreadsheet. This can be done using the Apache POI library of Java. We use the different classes and methods of POI library to set a print area of the spreadsheet. Usually, it takes from top left to the bottom right of the Excel Spreadsheets. It can be customized as pe
3 min read
How to Write Data into Excel Sheet using Java?
Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class. T
3 min read