如何使用Java将字体应用于单元格的内容。(How to apply fonts to the contents of a cell using Java.)

优质
小牛编辑
124浏览
2023-12-01

问题描述 (Problem Description)

如何使用Java将字体应用于单元格的内容。

解决方案 (Solution)

以下是使用Java将字体应用于单元格内容的程序。

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 DifferentFontsToCell {
   public static void main(String[] args)throws Exception {
      //Create a Work Book
      XSSFWorkbook workbook = new XSSFWorkbook();
      //Create a Spread Sheet
      XSSFSheet spreadsheet = workbook.createSheet("Fontstyle");
      XSSFRow row = spreadsheet.createRow(2);
      //Create a new font and alter it
      XSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short) 30);
      font.setFontName("IMPACT");
      font.setItalic(true);
      font.setColor(HSSFColor.BRIGHT_GREEN.index);
      //Set font into style
      XSSFCellStyle style = workbook.createCellStyle();
      style.setFont(font);
      // Create a cell with a value and set style to it.
      XSSFCell cell = row.createCell(1);
      cell.setCellValue("Font Style");
      cell.setCellStyle(style);
      FileOutputStream out = new FileOutputStream(new File("C:/poiexcel/fontstyle.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("fontstyle.xlsx written successfully");
   }
}

输出 (Output)

字体样式