How to Apply Different Styles to a Cell in a Spreadsheet using Java?
Last Updated :
27 Apr, 2021
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 provide built-in support for working with Excel files, so we need to look for open-source APIs for the job. It is an open-source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It contains classes and methods to decode the user input data or a file into MS Office documents. Here different styles can be applied like fonts, colors, cell merging, alignments, etc. to a cell in Excel using this concept in the Java program.
Apache POI Architecture: It consists of various components that make an architecture to form a working system:
- POIFS (Poor Obfuscation Implementation File System): This component is the basic factor of all other POI elements. It is used to read different files explicitly.
- HSSF (Horrible Spreadsheet Format): It is used to read and write xls format of MS-Excel files.
- XSSF (XML Spreadsheet Format): It is used for xlsx file format of MS-Excel.
- HPSF (Horrible Property Set Format): It is used to extract property sets of the MS-Office files.
- HWPF (Horrible Word Processor Format): It is used to read and write doc extension files of MS-Word.
- XWPF (XML Word Processor Format): It is used to read and write Docx extension files of MS-Word.
- HSLF (Horrible Slide Layout Format): It is used to read, create, and edit PowerPoint presentations.
- HDGF (Horrible Diagram Format): It contains classes and methods for MS-Visio binary files.
- HPBF (Horrible Publisher Format): It is used to read and write MS-Publisher files.
A Jar file is a Zip archive containing one or multiple java class files. This makes the usage of libraries handier. Directories and Jar files are added to the build path and available to the ClassLoader at runtime to find particular classes inside it. We generally use .jar files to distribute Java applications or libraries, in the form of Java class files and associated metadata and resources (text, images, etc.).
One can say JAR = JavaARchive
Approach:
- Step 1: Import the necessary .jar files like HSSF, XML and add them to your build path.
- Step 2: Create a workbook using “new XSSFWorkbook()” in which we have to create the spreadsheet or the Excel file using “workbook.createSheet('Sheet1')” in which we are going to apply different styles.

- Step 3: Apply the styles, here merge the cells using the command spreadsheet.addMergedRegion. We have to provide the range addresses of rows and columns as well as its parameter.
- Step 4: Now the next style in determining the cell alignment. For this, we have two commands
- "style1.setAlignment(XSSFCellStyle.ALIGN_LEFT)” for determining the alignment and
- "style1.setVerticalAlignment(XSSFCellStyle.VERTICAL_TOP)” for determining vertical alignment
- Step 5: For applying border to a cell, we can use “setBorderBottom/Left/Top/Right(XSSFCleeName.BorderName)”.
- Step 6: Change the border name in the parameter to go through different border styles.
- Step 7: For filling colors and adding patterns, first set the background color of the cell using “setFillBackgroundColor(HSSFColor.COLOR_NAME.index)”.
- Step 8: Then set the pattern whichever you like by “setFillPattern(XSSFCellStyle.PATTERN_NAME)”.
- Step 9: Finally, set the alignment using”setAlignment(XSSFCellStyle.ALIGN_TYPE);
Implementation: Carrying out the above procedural steps over the empty Excel file at the local directory already created.
- Create a Spread Sheet by creating an object of XSSFSheet
- Creating a row in the above XSSFSheet using createRow() method.
- Later on, setting the height of a row
- Creating an object of type XSSFCell and typecasting above row created to it.
- Setting cell values.
- Merging the cells.
- Aligning the cells.
- Justify the alignment.
- Bordering the cells.
- Filling colors in the cells.
- Creating a new file in the local directory by creating the object of FileOutputStream.
- Write to the above workbook created in the initial step.
- Close the connection of the file.
Example:
Java
// Java Program to apply different styles
// to a cell in a spreadsheet
// Importing java input/output classes
import java.io.File;
import java.io.FileOutputStream;
// Importing Apache POI modules
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
// Class- for styling cells
public class GFG {
// Main driver method
public static void main(String[] args) throws Exception
{
// Create a Work Book
XSSFWorkbook workbook = new XSSFWorkbook();
// Step 1: Create a Spread Sheet by
// creating an object of XSSFSheet
XSSFSheet spreadsheet
= workbook.createSheet("Sheet1");
// Step 2(a): Creating a row in above XSSFSheet
// using createRow() method
XSSFRow row = spreadsheet.createRow((short)1);
// Step 2(b): Setting height of a row
row.setHeight((short)800);
// Step 3: Creating an object of type XSSFCell and
// typecasting above row created to it
XSSFCell cell = (XSSFCell)row.createCell((short)1);
// Step 4: Setting cell values
cell.setCellValue("Merged cells");
// Step 5: MERGING CELLS
// This statement for merging cells
spreadsheet.addMergedRegion(new CellRangeAddress(
1, // first row (0-based)
1, // last row (0-based)
1, // first column (0-based)
4 // last column (0-based)
));
// Step 6: CELL Alignment
row = spreadsheet.createRow(5);
cell = (XSSFCell)row.createCell(0);
row.setHeight((short)800);
// 6(a) Top Left alignment
XSSFCellStyle style1 = workbook.createCellStyle();
spreadsheet.setColumnWidth(0, 8000);
style1.setAlignment(XSSFCellStyle.ALIGN_LEFT);
style1.setVerticalAlignment(
XSSFCellStyle.VERTICAL_TOP);
cell.setCellValue("Hi, I'm top left indent");
cell.setCellStyle(style1);
row = spreadsheet.createRow(6);
cell = (XSSFCell)row.createCell(1);
row.setHeight((short)800);
// 6(b) Center Align Cell Contents
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(
XSSFCellStyle.VERTICAL_CENTER);
cell.setCellValue("I'm Center Aligned indent");
cell.setCellStyle(style2);
row = spreadsheet.createRow(7);
cell = (XSSFCell)row.createCell(2);
row.setHeight((short)800);
// 6(c) Bottom Right alignment
XSSFCellStyle style3 = workbook.createCellStyle();
style3.setAlignment(XSSFCellStyle.ALIGN_RIGHT);
style3.setVerticalAlignment(
XSSFCellStyle.VERTICAL_BOTTOM);
cell.setCellValue("I'm Bottom Right indent");
cell.setCellStyle(style3);
row = spreadsheet.createRow(8);
cell = (XSSFCell)row.createCell(3);
// Step 7: Justifying Alignment
XSSFCellStyle style4 = workbook.createCellStyle();
style4.setAlignment(XSSFCellStyle.ALIGN_JUSTIFY);
style4.setVerticalAlignment(
XSSFCellStyle.VERTICAL_JUSTIFY);
cell.setCellValue(
"I'm Justify indent nice to meet you");
cell.setCellStyle(style4);
// Step 8: CELL BORDER
row = spreadsheet.createRow((short)10);
row.setHeight((short)800);
cell = (XSSFCell)row.createCell((short)1);
cell.setCellValue("BORDER");
XSSFCellStyle style5 = workbook.createCellStyle();
style5.setBorderBottom(XSSFCellStyle.BORDER_THICK);
style5.setBottomBorderColor(
IndexedColors.BLUE.getIndex());
style5.setBorderLeft(XSSFCellStyle.BORDER_DOUBLE);
style5.setLeftBorderColor(
IndexedColors.GREEN.getIndex());
style5.setBorderRight(XSSFCellStyle.BORDER_HAIR);
style5.setRightBorderColor(
IndexedColors.RED.getIndex());
style5.setBorderTop(XSSFCellStyle.BIG_SPOTS);
style5.setTopBorderColor(
IndexedColors.Black.getIndex());
cell.setCellStyle(style5);
// Step 9: Fill Colors
// 9(a) Background color
row = spreadsheet.createRow((short)10);
cell = (XSSFCell)row.createCell((short)1);
XSSFCellStyle style6 = workbook.createCellStyle();
style6.setFillBackgroundColor(HSSFColor.BLUE.index);
style6.setFillPattern(
XSSFCellStyle.FILL_HORIZONTAL_CROSS_HATCH);
style6.setAlignment(XSSFCellStyle.ALIGN_FILL);
spreadsheet.setColumnWidth(1, 8000);
cell.setCellValue("FILL HORIZONTAL CROSS HATCH");
cell.setCellStyle(style6);
// 9(b) Foreground color
row = spreadsheet.createRow((short)12);
cell = (XSSFCell)row.createCell((short)1);
XSSFCellStyle style7 = workbook.createCellStyle();
style7.setFillForegroundColor(
HSSFColor.GREEN.index);
style7.setFillPattern(
XSSFCellStyle.THIN_VERTICAL_STRIPE);
style7.setAlignment(XSSFCellStyle.ALIGN_FILL);
cell.setCellValue("THIN VERTICAL STRIPE");
cell.setCellStyle(style7);
// Step 10: Creating a new file in the local
// directory by creating object of FileOutputStream
FileOutputStream out = new FileOutputStream(
new File("C:/poiexcel/stlingcells.xlsx"));
// Step 11: Write to above workbook created in
// initial step
workbook.write(out);
// Step 12: Close the file connection
out.close();
// Display message for console window when
// program is successfully executed
System.out.println("gfg.xlsx success");
}
}
Output
Similar Reads
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 Set Direction to the Text in Cell using Java?
Apache POI is an open-source library by Apache which can be used to create, modify and display files MS office file in Java. It provides classes and methods to do so. This API provides various components such as POIFS (Poor Obfuscation Implementation File System), HSSF (Horrible Spreadsheet Format),
3 min read
How to Apply Borders to the Text in a Word Document using Java?
Java Library Apache POI will be used to apply borders to text in a Word Document in java. Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as
3 min read
How to Apply Fonts to the Contents of a Cell Using Java?
In this article, we will learn how to apply the custom font and various styles associated with it using Java and Apache POI (a Java API which is very useful to handle the Microsoft Documents). Approach: Writing a file using POI is very simple and involve following steps: Create a workbook.Create a s
2 min read
How to Add Hyperlink to the Contents of a Cell using Java?
Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents. Installation: There are two ways to install the Apache POI dependency in our java project: Download below mentioned Jar files from poi.apache.org/downlo
2 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
Java Program to Draw a Shape in Excel Sheet using Apache POI
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
4 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
How to Format the Text in a Word Document using Java?
Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint, and Excel. First do install Apache in order to import modules as per th
3 min read
Formatting the Content of a Cell in a Table of PDF using Java
iText is a Java library developed, to access and manipulate PDF files, that is to extract and modify the PDF content. iText is a Java library originally created by Bruno Lowagie which allows creating, reading, and manipulating PDF files. Java allows incorporating various fully developed packages and
4 min read