Open In App

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:

  1. Create a workbook.
  2. Create a spreadsheet in workbook.
  3. Create a font and apply styling to it in the spreadsheet.
  4. Create a cell and apply value to it.
  5. Add cells in spreadsheet.
  6. Repeat step 3 to 5 to write more data

Example:






// import Statements
import java.io.File;
import java.io.FileOutputStream;
  
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  
public class FontsInExcel {
    public static void fontFile()
    
          // Created a workbook
        XSSFWorkbook myWorkbook = new XSSFWorkbook();
  
        // Created a spreadsheet
        XSSFSheet newSpreadsheet
            = myWorkbook.createSheet("Book");
        XSSFRow row = newSpreadsheet.createRow(1);
  
        // Created a new font
        XSSFFont font = myWorkbook.createFont();
  
        // Setting Font Properties
        font.setFontHeightInPoints((short)30);
        font.setFontName("Arial");
        font.setBold(true);
        font.setItalic(true);
        font.setColor(HSSFColor.BRIGHT_RED.index);
  
        // Set created font into style
        XSSFCellStyle cellStyle
            = myWorkbook.createCellStyle();
        cellStyle.setFont(font);
  
        // Create a cell with a custom value and set style
        // to it.
        XSSFCell myCell = row.createCell(6);
        myCell.setCellValue("New Font");
        myCell.setCellStyle(cellStyle);
  
        // Opening and changing the File
        FileOutputStream file = new FileOutputStream(
            new File("C:/Book.xlsx"));
  
        myWorkbook.write(file);
        file.close();
    }
    public static void main(String[] args) throws Exception
    {
        fontFile();
    }
}

Output


Article Tags :