在Java中设置Excel字体
在Java中操作Excel并设置字体,通常使用Apache POI库,以下是几种常见的设置字体的方法:
基本字体设置
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
// 创建行和单元格
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hello World");
// 创建字体样式
Font font = workbook.createFont();
font.setFontName("Arial"); // 设置字体名称
font.setFontHeightInPoints((short) 12); // 设置字体大小
font.setColor(IndexedColors.RED.getIndex()); // 设置字体颜色
font.setBold(true); // 设置粗体
font.setItalic(true); // 设置斜体
// 应用字体到单元格样式
CellStyle style = workbook.createCellStyle();
style.setFont(font);
// 应用样式到单元格
cell.setCellStyle(style);
使用预定义字体颜色
Font font = workbook.createFont(); font.setColor(IndexedColors.BLUE.getIndex()); // 使用预定义颜色
自定义字体颜色
Font font = workbook.createFont(); font.setColor(new XSSFColor(new java.awt.Color(128, 0, 128), null)); // 自定义紫色
下划线设置
Font font = workbook.createFont(); font.setUnderline(Font.U_SINGLE); // 单下划线 // 或 font.setUnderline(Font.U_DOUBLE); // 双下划线
完整示例
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
public class ExcelFontExample {
public static void main(String[] args) throws Exception {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Font Example");
// 创建标题行
Row titleRow = sheet.createRow(0);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellValue("标题");
// 设置标题字体
Font titleFont = workbook.createFont();
titleFont.setFontName("微软雅黑");
titleFont.setFontHeightInPoints((short) 16);
titleFont.setBold(true);
titleFont.setColor(IndexedColors.DARK_BLUE.getIndex());
CellStyle titleStyle = workbook.createCellStyle();
titleStyle.setFont(titleFont);
titleCell.setCellStyle(titleStyle);
// 创建内容行
Row contentRow = sheet.createRow(1);
Cell contentCell = contentRow.createCell(0);
contentCell.setCellValue("这是内容文本");
// 设置内容字体
Font contentFont = workbook.createFont();
contentFont.setFontName("宋体");
contentFont.setFontHeightInPoints((short) 12);
contentFont.setColor(IndexedColors.BLACK.getIndex());
contentFont.setItalic(true);
CellStyle contentStyle = workbook.createCellStyle();
contentStyle.setFont(contentFont);
contentCell.setCellStyle(contentStyle);
// 保存文件
try (FileOutputStream out = new FileOutputStream("ExcelFontExample.xlsx")) {
workbook.write(out);
}
workbook.close();
}
}
注意事项
- 对于
.xlsx格式,使用XSSFWorkbook;对于.xls格式,使用HSSFWorkbook - 字体设置需要通过
CellStyle应用到单元格 - 在处理大量样式时,建议重用
CellStyle对象以提高性能 - 某些字体属性可能在不同Excel版本中有兼容性问题
代码展示了在Java中使用Apache POI设置Excel字体样式的基本方法,你可以根据需要调整字体名称、大小、颜色等属性。
