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
How to Create Pivot Table in Excel using Java? A pivot table is needed to quickly analyze data of a table with very little effort (and no formulas) and sometimes not everyone has time to look at the data in the table and see whatâs going on and use it to build good-looking reports for large data sets in an Excel worksheet. Let's discuss a step-b
5 min read
How to Create Hyperlink in Spreadsheet using Java? Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java programs. It is an open-source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java programs. It contains classes and methods
4 min read
How to Create Pivot Chart from Pivot Table in Excel using Java? A Pivot Chart is used to analyze data of a table with very little effort (and no formulas) and it gives you the big picture of your raw data. It allows you to analyze data using various types of graphs and layouts. It is considered to be the best chart during a business presentation that involves hu
4 min read
How to Create Different Data Format of Cells in a Spreadsheet Using Java? Formatting in excel is a neat trick in excel which is used to change the appearance of the data represented in the worksheet, formatting can be done in multiple ways such as we can format the data of the cells by using the styles. By default, all worksheet cells are formatted with the General number
4 min read
How to Create a Formula in Excel using Java? Apache POI is a popular open-source Java library that provides programmers with APIs for creating, modifying, and editing MS Office files. Excel is very excellent at calculating formulas. And perhaps most Excel documents have formulas embedded. Therefore, itâs trivial that on a fine day, you have to
3 min read
How to Insert a Picture in a Cell in MS Excel? Every day in business or any other field lots of information are there that are required to store for future use. For anyone, it is very difficult to remember that information for a long time. Earlier data and information are stored in a form of a register, file, or by paperwork but finding it may b
4 min read