Open In App

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 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:



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:

Implementation: Carrying out the above procedural steps over the empty Excel file at the local directory already created.

  1. Create a Spread Sheet by creating an object of XSSFSheet
  2. Creating a row in the above XSSFSheet using createRow() method.
    • Later on, setting the height of a row
  3. Creating an object of type XSSFCell and typecasting above row created to it.
  4. Setting cell values.
  5. Merging the cells.
  6. Aligning the cells.
  7. Justify the alignment.
  8. Bordering the cells.
  9. Filling colors in the cells.
  10. Creating a new file in the local directory by creating the object of FileOutputStream.
  11. Write to the above workbook created in the initial step.
  12. Close the connection of the file.

Example:




// 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

 

 


Article Tags :