How to Fill Background Color of Cells in Excel using Java and Apache POI?
Apache POI is an open-source java library to create and manipulate various file formats based on Microsoft Office. 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. In this article, we are going to discuss how to fill the background colors and foreground colors of the cells in Excel using the Apache POI. First, we will create an Excel file and enter the cell values and add the colors for each cell. Apache POI is providing the createcellstyle method in XSSFCellStyle.
To work with the Apache POI, we need the following software in our system
- Check that your system has Java JDK
- Install the Eclipse IDE for Java developers from here.
- Create a Maven project
For creating a maven project Check this How to Create a Selenium Maven Project with Eclipse to Open Chrome Browser?
- Add the Apache POI and Apache-ooxml dependency into the POM.xml file
After installing all the dependencies, we are now ready to write the code, it is styled using the creatcellstyle method. The style method provides many designs such as setFillBackgroundColor, setFillForegroundColor and setFillPattern.
This method enables us to set the background color of the cell, the Apache POI dependency provides us with the Indexed color class that has all the colors.
This method is also similar to the setBackgroundColor.
This method provides various types of design patterns like Big spots, Briks, Diamond, Fine Dots, etc.
Program for fill background and foreground colors in Excel using Apache POI
- Create a sheet and row for the created sheet.
- After that create the style for the workbook
- Then style the background and foreground by setFillBackgroundColor and setFillPattern, then give the cell value and cell style.
- After the styles are done now create the File output stream
- Write the cell data into the output stream.
Now run the code in the eclipse, we can get the output as style is created and we can notice that an Excel sheet is created in the specified location with the cell styles.
Please Login to comment...