Java excel cell format

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.DataFormat;

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 GFG {

    public static void main(String[] args) throws Exception

    {

        String excelfilename = "GeeksForGeeks.xlsx";

        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet spreadsheet

            = workbook.createSheet("Sheet1");

        XSSFRow row;

        XSSFCell cell;

        XSSFCellStyle style;

        DataFormat format = workbook.createDataFormat();

        int rowNum = 0;

        int colNum = 0;

        row = spreadsheet.createRow(rowNum++);

        cell = row.createCell(colNum);

        cell.setCellValue(11111.25);

        style = workbook.createCellStyle();

        style.setDataFormat(format.getFormat("0.0"));

        cell.setCellStyle(style);

        row = spreadsheet.createRow(rowNum++);

        cell = row.createCell(colNum);

        cell.setCellValue(11111.25);

        style = workbook.createCellStyle();

        style.setDataFormat(format.getFormat("#,##0.0000"));

        cell.setCellStyle(style);

        try {

            FileOutputStream outputfile

                = new FileOutputStream(excelfilename);

            workbook.write(outputfile);

            outputfile.close();

            System.out.println(excelfilename

                               + " is written successfully");

        }

        catch (FileNotFoundException e) {

            System.out.println("ERROR!! " + e.getMessage());

        }

    }

}

Learn to read excel, write excel, evaluate formula cells and apply custom formatting to the generated excel files using Apache POI library with examples.

If we are building software for the HR or Finance domain, there is usually a requirement for generating excel reports across management levels. Apart from reports, we can also expect some input data for the applications coming in the form of excel sheets and the application is expected to support this requirement.

Apache POI is a well-trusted library among many other open-source libraries to handle such usecases involving excel files. Please note that, in addition, we can read and write MS Word and MS PowerPoint files also using the Apache POI library.

This Apache POI tutorial will discuss some everyday excel operations in real-life applications.

  1. 1. Maven Dependency
  2. 2. Important Classes in POI Library
  3. 3. Writing an Excel File
  4. 4. Reading an Excel File
  5. 5. Add and Evaluate Formula Cells
  6. 6. Formatting the Cells
  7. 7. Conclusion

1. Maven Dependency

If we are working on a maven project, we can include the Apache POI dependencies in pom.xml file using this:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>5.2.2</version>
</dependency>

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>5.2.2</version>
</dependency>

2. Important Classes in POI Library

  1. HSSF, XSSF and XSSF classes

    Apache POI main classes usually start with either HSSF, XSSF or SXSSF.

    • HSSF – is the POI Project’s pure Java implementation of the Excel 97(-2007) file format. e.g., HSSFWorkbook, HSSFSheet.
    • XSSF – is the POI Project’s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format. e.g., XSSFWorkbook, XSSFSheet.
    • SXSSF (since 3.8-beta3) – is an API-compatible streaming extension of XSSF to be used when huge spreadsheets have to be produced and heap space is limited. e.g., SXSSFWorkbook, SXSSFSheet. SXSSF achieves its low memory footprint by limiting access to the rows within a sliding window, while XSSF gives access to all rows in the document.
  2. Row and Cell

    Apart from the above classes, Row and Cell interact with a particular row and a particular cell in an excel sheet.

  3. Styling Related Classes

    A wide range of classes like CellStyle, BuiltinFormats, ComparisonOperator, ConditionalFormattingRule, FontFormatting, IndexedColors, PatternFormatting, SheetConditionalFormatting etc. are used when you have to add formatting to a sheet, primarily based on some rules.

  4. FormulaEvaluator

    Another helpful class FormulaEvaluator is used to evaluate the formula cells in an excel sheet.

3. Writing an Excel File

I am taking this example first so we can reuse the excel sheet created by this code in further examples.

Writing excel using POI is very simple and involves the following steps:

  1. Create a workbook
  2. Create a sheet in workbook
  3. Create a row in sheet
  4. Add cells to sheet
  5. Repeat steps 3 and 4 to write more data

It seems very simple, right? Let’s have a look at the code doing these steps.

Java program to write an excel file using Apache POI library.

package com.howtodoinjava.demo.poi;
//import statements
public class WriteExcelDemo 
{
    public static void main(String[] args) 
    {
        //Blank workbook
        XSSFWorkbook workbook = new XSSFWorkbook(); 
         
        //Create a blank sheet
        XSSFSheet sheet = workbook.createSheet("Employee Data");
          
        //This data needs to be written (Object[])
        Map<String, Object[]> data = new TreeMap<String, Object[]>();
        data.put("1", new Object[] {"ID", "NAME", "LASTNAME"});
        data.put("2", new Object[] {1, "Amit", "Shukla"});
        data.put("3", new Object[] {2, "Lokesh", "Gupta"});
        data.put("4", new Object[] {3, "John", "Adwards"});
        data.put("5", new Object[] {4, "Brian", "Schultz"});
          
        //Iterate over data and write to sheet
        Set<String> keyset = data.keySet();
        int rownum = 0;
        for (String key : keyset)
        {
            Row row = sheet.createRow(rownum++);
            Object [] objArr = data.get(key);
            int cellnum = 0;
            for (Object obj : objArr)
            {
               Cell cell = row.createCell(cellnum++);
               if(obj instanceof String)
                    cell.setCellValue((String)obj);
                else if(obj instanceof Integer)
                    cell.setCellValue((Integer)obj);
            }
        }
        try
        {
            //Write the workbook in file system
            FileOutputStream out = new FileOutputStream(new File("howtodoinjava_demo.xlsx"));
            workbook.write(out);
            out.close();
            System.out.println("howtodoinjava_demo.xlsx written successfully on disk.");
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}
poi-demo-write-file

See Also: Appending Rows to Excel

4. Reading an Excel File

Reading an excel file using POI is also very simple if we divide this into steps.

  1. Create workbook instance from an excel sheet
  2. Get to the desired sheet
  3. Increment row number
  4. iterate over all cells in a row
  5. repeat steps 3 and 4 until all data is read

Let’s see all the above steps in code. I am writing the code to read the excel file created in the above example. It will read all the column names and the values in it – cell by cell.

Java program to read an excel file using Apache POI library.

package com.howtodoinjava.demo.poi;
//import statements
public class ReadExcelDemo 
{
    public static void main(String[] args) 
    {
        try
        {
            FileInputStream file = new FileInputStream(new File("howtodoinjava_demo.xlsx"));
 
            //Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook = new XSSFWorkbook(file);
 
            //Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);
 
            //Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) 
            {
                Row row = rowIterator.next();
                //For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();
                 
                while (cellIterator.hasNext()) 
                {
                    Cell cell = cellIterator.next();
                    //Check the cell type and format accordingly
                    switch (cell.getCellType()) 
                    {
                        case Cell.CELL_TYPE_NUMERIC:
                            System.out.print(cell.getNumericCellValue() + "t");
                            break;
                        case Cell.CELL_TYPE_STRING:
                            System.out.print(cell.getStringCellValue() + "t");
                            break;
                    }
                }
                System.out.println("");
            }
            file.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
}

Program Output:

ID      NAME        LASTNAME
1.0     Amit        Shukla  
2.0     Lokesh      Gupta   
3.0     John        Adwards 
4.0     Brian       Schultz 

See Also: Apache POI – Read an Excel File using SAX Parser

5. Add and Evaluate Formula Cells

When working on complex excel sheets, we encounter many cells with formulas to calculate their values. These are formula cells. Apache POI also has excellent support for adding formula cells and evaluating already present formula cells.

Let’s see one example of how to add formula cells in excel?

The sheet has four cells in a row and the fourth one in the multiplication of all the previous 3 rows. So the formula will be: A2*B2*C2 (in the second row)

Java program to add formula in an excel file using Apache POI library.

public static void main(String[] args) 
{
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
  
    Row header = sheet.createRow(0);
    header.createCell(0).setCellValue("Pricipal");
    header.createCell(1).setCellValue("RoI");
    header.createCell(2).setCellValue("T");
    header.createCell(3).setCellValue("Interest (P r t)");
      
    Row dataRow = sheet.createRow(1);
    dataRow.createCell(0).setCellValue(14500d);
    dataRow.createCell(1).setCellValue(9.25);
    dataRow.createCell(2).setCellValue(3d);
    dataRow.createCell(3).setCellFormula("A2*B2*C2");
      
    try {
        FileOutputStream out =  new FileOutputStream(new File("formulaDemo.xlsx"));
        workbook.write(out);
        out.close();
        System.out.println("Excel with foumula cells written successfully");
          
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Similarly, we want to read a file with formula cells and use the following logic to evaluate formula cells.

Java program to evaluate formula in an excel file using Apache POI library.

public static void readSheetWithFormula()
{
    try
    {
        FileInputStream file = new FileInputStream(new File("formulaDemo.xlsx"));
 
        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);
 
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
         
        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);
 
        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) 
        {
            Row row = rowIterator.next();
            //For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
             
            while (cellIterator.hasNext()) 
            {
                Cell cell = cellIterator.next();
                //Check the cell type after eveluating formulae
                //If it is formula cell, it will be evaluated otherwise no change will happen
                switch (evaluator.evaluateInCell(cell).getCellType()) 
                {
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue() + "tt");
                        break;
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + "tt");
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        //Not again
                        break;
                }
            }
            System.out.println("");
        }
        file.close();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Program Output:

Pricipal        RoI         T       Interest (P r t)        
14500.0         9.25        3.0     402375.0  
poi-demo-write-formula

6. Formatting the Cells

So far we have seen examples of reading/writing and excel files using Apache POI. But, when creating a report in an excel file, it is essential to add formatting on cells that fit into any pre-determined criteria.

This formatting can be a different coloring based on a specific value range, expiry date limit etc.

In the below examples, we are taking a couple of such cell formatting examples for various purposes.

6.1. Cell value in a specific range

This code will color any cell in a range whose value is between a configured range. [e.g., between 50 and 70]

static void basedOnValue(Sheet sheet) 
{
    //Creating some random values
    sheet.createRow(0).createCell(0).setCellValue(84);
    sheet.createRow(1).createCell(0).setCellValue(74);
    sheet.createRow(2).createCell(0).setCellValue(50);
    sheet.createRow(3).createCell(0).setCellValue(51);
    sheet.createRow(4).createCell(0).setCellValue(49);
    sheet.createRow(5).createCell(0).setCellValue(41);
 
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
 
    //Condition 1: Cell Value Is   greater than  70   (Blue Fill)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule(ComparisonOperator.GT, "70");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.BLUE.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    //Condition 2: Cell Value Is  less than      50   (Green Fill)
    ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.LT, "50");
    PatternFormatting fill2 = rule2.createPatternFormatting();
    fill2.setFillBackgroundColor(IndexedColors.GREEN.index);
    fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A1:A6")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1, rule2);
}
poi-demo-formatting-1

6.2. Highlight Duplicate Values

Highlight all cells which have duplicate values in observed cells.

static void formatDuplicates(Sheet sheet) {
    sheet.createRow(0).createCell(0).setCellValue("Code");
    sheet.createRow(1).createCell(0).setCellValue(4);
    sheet.createRow(2).createCell(0).setCellValue(3);
    sheet.createRow(3).createCell(0).setCellValue(6);
    sheet.createRow(4).createCell(0).setCellValue(3);
    sheet.createRow(5).createCell(0).setCellValue(5);
    sheet.createRow(6).createCell(0).setCellValue(8);
    sheet.createRow(7).createCell(0).setCellValue(0);
    sheet.createRow(8).createCell(0).setCellValue(2);
    sheet.createRow(9).createCell(0).setCellValue(8);
    sheet.createRow(10).createCell(0).setCellValue(6);
 
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
 
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("COUNTIF($A$2:$A$11,A2)>1");
    FontFormatting font = rule1.createFontFormatting();
    font.setFontStyle(false, true);
    font.setFontColorIndex(IndexedColors.BLUE.index);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A2:A11")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1);
 
    sheet.getRow(2).createCell(1).setCellValue("<== Duplicates numbers in the column are highlighted.  " +
            "Condition: Formula Is =COUNTIF($A$2:$A$11,A2)>1   (Blue Font)");
}
poi-demo-formatting-2

6.3. Alternate Color Rows in Different Colors

A simple code to color each alternate row in a different color.

static void shadeAlt(Sheet sheet) {
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
 
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("MOD(ROW(),2)");
    PatternFormatting fill1 = rule1.createPatternFormatting();
    fill1.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.index);
    fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A1:Z100")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1);
 
    sheet.createRow(0).createCell(1).setCellValue("Shade Alternating Rows");
    sheet.createRow(1).createCell(1).setCellValue("Condition: Formula Is  =MOD(ROW(),2)   (Light Green Fill)");
}
poi-demo-formatting-3

6.4. Color amounts that are going to expire in the next 30 days

A handy code for financial projects which keeps track of deadlines.

static void expiryInNext30Days(Sheet sheet) 
{
    CellStyle style = sheet.getWorkbook().createCellStyle();
    style.setDataFormat((short)BuiltinFormats.getBuiltinFormat("d-mmm"));
 
    sheet.createRow(0).createCell(0).setCellValue("Date");
    sheet.createRow(1).createCell(0).setCellFormula("TODAY()+29");
    sheet.createRow(2).createCell(0).setCellFormula("A2+1");
    sheet.createRow(3).createCell(0).setCellFormula("A3+1");
 
    for(int rownum = 1; rownum <= 3; rownum++) sheet.getRow(rownum).getCell(0).setCellStyle(style);
 
    SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
 
    // Condition 1: Formula Is   =A2=A1   (White Font)
    ConditionalFormattingRule rule1 = sheetCF.createConditionalFormattingRule("AND(A2-TODAY()>=0,A2-TODAY()<=30)");
    FontFormatting font = rule1.createFontFormatting();
    font.setFontStyle(false, true);
    font.setFontColorIndex(IndexedColors.BLUE.index);
 
    CellRangeAddress[] regions = {
            CellRangeAddress.valueOf("A2:A4")
    };
 
    sheetCF.addConditionalFormatting(regions, rule1);
 
    sheet.getRow(0).createCell(1).setCellValue("Dates within the next 30 days are highlighted");
}
poi-demo-formatting-4

I am ending this apache poi tutorial here to keep the post within a limit.

7. Conclusion

In this tutorial, we learned to read excel, write excel, set and evaluate formula cells, and format the cells with color codings using the Apache POI library.

Happy Learning !!

Source Code on Github

In addition to @BlondeCode answer, here are the list of all available formats that you can get with
creationHelper.createDataFormat().getFormat((short) index)

0 = «General»
1 = «0»
2 = «0.00»
3 = «#,##0»
4 = «#,##0.00»
5 = «»$»#,##0_);(«$»#,##0)»
6 = «»$»#,##0_);Red»
7 = «»$»#,##0.00_);(«$»#,##0.00)»
8 = «»$»#,##0.00_);Red»
9 = «0%»
10 = «0.00%»
11 = «0.00E+00»
12 = «# ?/?»
13 = «# ??/??»
14 = «m/d/yy»
15 = «d-mmm-yy»
16 = «d-mmm»
17 = «mmm-yy»
18 = «h:mm AM/PM»
19 = «h:mm:ss AM/PM»
20 = «h:mm»
21 = «h:mm:ss»
22 = «m/d/yy h:mm»
23-36 = reserved
37 = «#,##0_);(#,##0)»
38 = «#,##0_);Red»
39 = «#,##0.00_);(#,##0.00)»
40 = «#,##0.00_);Red»
41 = «(* #,##0);(* (#,##0);(* «-«);(@
42 = «
(«$»* #,##0_);(«$»* (#,##0);(«$»* «-«);(@
43 = «
(* #,##0.00_);(* (#,##0.00);(* «-«??);(@
44 = «
(«$»* #,##0.00_);(«$»* (#,##0.00);(«$»* «-«??);(@_)»
45 = «mm:ss»
46 = «[h]:mm:ss»
47 = «mm:ss.0»
48 = «##0.0E+0»
49 = «@»

And from index 164, there are your custom patterns

Aspose.Cells for Java API can be used to apply various kind of formatting in Excel cell programmatically without the need to install or automate Microsoft Excel or without using VBA or VSTO.

Article Description

The purpose of this article is to explain how developers can apply these formatting in Excel cell using Java.

  • Bold
  • Italic
  • Underline
  • Double Underline

Supported Platforms

Aspose.Cells API supports number of platforms e.g. Java, .NET, C++, Android, JavaScript, PHP etc. Besides, Aspose.Cells is available in Cloud as REST or RESTful APIs.

Excel Cell Formatting — Bold

Please follow these steps to make the text or value of the cell as bold. Also see the code example for more help.

  • Get the style of the cell.
  • Set the Style.Font.IsBold as true.
  • Set the style of the cell.
// Get style of cell.
Style st = cell.getStyle();
// Set the font bold.
st.getFont().setBold(true);
// Set the style of cell.
cell.setStyle(st);

Excel Cell Formatting — Italic

Please follow these steps to make the text or value of the cell as italic. Also see the code example for more help.

  • Get the style of the cell.
  • Set the Style.Font.IsItalic as true.
  • Set the style of the cell.
// Get style of cell.
Style st = cell.getStyle();
// Set the font italic.
st.getFont().setItalic(true);
// Set the style of cell.
cell.setStyle(st);

Excel Cell Formatting — Underline

Please follow these steps to make the text or value of the cell as underline. Also see the code example for more help.

  • Get the style of the cell.
  • Set the Style.Font.Underline as FontUnderlineType.SINGLE.
  • Set the style of the cell.
// Get style of cell.
Style st = cell.getStyle();
// Set the font underline.
st.getFont().setUnderline(FontUnderlineType.SINGLE);
// Set the style of cell.
cell.setStyle(st);

Excel Cell Formatting — Double Underline

Please follow these steps to make the text or value of the cell as double underline. Also see the code example for more help.

  • Get the style of the cell.
  • Set the Style.Font.Underline as FontUnderlineType.DOUBLE.
  • Set the style of the cell.
// Get style of cell.
Style st = cell.getStyle();
// Set the font double underline.
st.getFont().setUnderline(FontUnderlineType.DOUBLE);
// Set the style of cell.
cell.setStyle(st);

Sample Code

Here is the complete sample code that applies bold, italic, underline, double underline formatting on Excel cell. Please also see the snapshot of the output Excel file generated by the code given below.

// Directory path for output.
String dirPath = «D:\Download\»;
// Create workbook object.
com.aspose.cells.Workbook wb = new Workbook();
// Get default style of the workbook.
Style st = wb.getDefaultStyle();
// Set the font name, size, vertical and
// horizontal alignment of the style.
st.getFont().setName(«Calibri»);
st.getFont().setSize(11);
st.setVerticalAlignment(TextAlignmentType.CENTER);
st.setHorizontalAlignment(TextAlignmentType.CENTER);
// Set the default style of the workbook.
wb.setDefaultStyle(st);
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Set the width of column E.
ws.getCells().setColumnWidth(4, 50);
// Set the height of rows 4, 5, 6 and 7.
ws.getCells().setRowHeight(3, 50);
ws.getCells().setRowHeight(4, 50);
ws.getCells().setRowHeight(5, 50);
ws.getCells().setRowHeight(6, 50);
/*
########################################################
START: Bold Text
########################################################
*/
// Access cell E4.
Cell cell = ws.getCells().get(«E4»);
// Add some text in cell.
cell.putValue(«Bold Text»);
// Access style of cell.
st = cell.getStyle();
// Set the font size.
st.getFont().setSize(24);
// Set the font bold.
st.getFont().setBold(true);
// Set the style of cell.
cell.setStyle(st);
/*
########################################################
START: Italic Text
########################################################
*/
// Access cell E5.
cell = ws.getCells().get(«E5»);
// Add some text in cell.
cell.putValue(«Italic Text»);
// Access style of cell.
st = cell.getStyle();
// Set the font size.
st.getFont().setSize(24);
// Set the font italic.
st.getFont().setItalic(true);
// Set the style of cell.
cell.setStyle(st);
/*
########################################################
START: Underline Text
########################################################
*/
// Access cell E6.
cell = ws.getCells().get(«E6»);
// Add some text in cell.
cell.putValue(«Underline Text»);
// Access style of cell.
st = cell.getStyle();
// Set the font size.
st.getFont().setSize(24);
// Set the font underline.
st.getFont().setUnderline(FontUnderlineType.SINGLE);
// Set the style of cell.
cell.setStyle(st);
/*
########################################################
START: Double Underline Text
########################################################
*/
// Access cell E7.
cell = ws.getCells().get(«E7»);
// Add some text in cell.
cell.putValue(«Double Underline Text»);
// Access style of cell.
st = cell.getStyle();
// Set the font size.
st.getFont().setSize(24);
// Set the font double underline.
st.getFont().setUnderline(FontUnderlineType.DOUBLE);
// Set the style of cell.
cell.setStyle(st);
/*
########################################################
START: Save Workbook
########################################################
*/
// Save the workbook in XLSX format.
// You can also save it to XLS or other formats.
wb.save(dirPath + «outputExcelCellFormattingBoldItalicUnderline.xlsx», SaveFormat.XLSX);

Snapshot of Output Excel file

Here is the snapshot of the output Excel file generated with the above code for your reference.

See also

  • Excel Cell Data Formatting
  • Forum — Aspose.Cells Product Family

This example demonstrate how to use HSSFCellStyle and HSSFFont to format the cell style in Excel document. Using this class we can define cell border, foreground and background color. We can also define the font we used to display the cell value.

package org.kodejava.poi;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;

import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelCellFormat {
    public static void main(String[] args) {
        // Create an instance of workbook and sheet
        try (HSSFWorkbook workbook = new HSSFWorkbook()) {
            HSSFSheet sheet = workbook.createSheet();

            // Create an instance of HSSFCellStyle which will be used to format the
            // cell. Here we define the cell top and bottom border, and we also
            // define the background color.
            HSSFCellStyle style = workbook.createCellStyle();
            style.setBorderTop(BorderStyle.DOUBLE);
            style.setBorderBottom(BorderStyle.THIN);
            style.setFillForegroundColor(
                    HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            // We also define the font that we are going to use for displaying the
            // data of the cell. We set the font to ARIAL with 20pt in size and
            // make it BOLD and give blue as the color.
            HSSFFont font = workbook.createFont();
            font.setFontName(HSSFFont.FONT_ARIAL);
            font.setFontHeightInPoints((short) 20);
            font.setBold(true);
            font.setColor(HSSFColor.HSSFColorPredefined.BLUE.getIndex());
            style.setFont(font);

            // We create a simple cell, set its value and apply the cell style.
            HSSFRow row = sheet.createRow(1);
            HSSFCell cell = row.createCell(1);
            cell.setCellValue(new HSSFRichTextString("Hi there... It's me again!"));
            cell.setCellStyle(style);
            sheet.autoSizeColumn((short) 1);

            // Finally, we write out the workbook into an Excel file.
            try (FileOutputStream fos = new FileOutputStream("ExcelDemo.xls")) {
                workbook.write(fos);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>5.2.3</version>
</dependency>

Maven Central

  • Author
  • Recent Posts

A programmer, runner, recreational diver, live in the island of Bali, Indonesia. Programming in Java, Spring, Hibernate / JPA. You can support me working on this project, buy me a cup of coffee ☕, every little bit helps, thank you 🙏

Views: 41,107

Понравилась статья? Поделить с друзьями:
  • Javascript and excel vba
  • Java download to excel
  • Java чтение word файла
  • Java create word document
  • Java таблица как в excel