Author:赵志乾
Date:2024-08-15
Declaration:All Right Reserved!!!
1. 问题描述
使用EasyExcel默认的设定输出时,中文字体显得比较怪异。
2. 解决方案
本质是单元格样式的设置问题,在EasyExcel中,可以通过实现WriteHandler接口或使用EasyExcel提供的注解以及WriteCellStyle来自定义样式。由于EasyExcel本身提供了HorizontalCellStyleStrategy,其允许开发者自定义表头和内容的样式,功能上足以满足简单需求。
设定表头样式为楷体14号加粗居中对齐、内容样式为楷体11号居中对齐,代码如下:
private static HorizontalCellStyleStrategy horizontalCellStyleStrategy;
static {
WriteFont headFont = new WriteFont();
headFont.setFontName("楷体");
headFont.setFontHeightInPoints((short) 14);
headFont.setBold(true);
WriteFont contentFont = new WriteFont();
contentFont.setFontName("楷体");
contentFont.setFontHeightInPoints((short) 11);
contentFont.setBold(false);
WriteCellStyle headCellStyle = new WriteCellStyle();
headCellStyle.setWriteFont(headFont);
headCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentCellStyle = new WriteCellStyle();
contentCellStyle.setWriteFont(contentFont);
contentCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headCellStyle, contentCellStyle);
}
public static void write(String fullName, String sheetName, List<T> items, Class<T> clazz){
EasyExcel.write(fullName, clazz)
.registerWriteHandler(horizontalCellStyleStrategy)
.registerConverter(new DateTimeConverter())
.sheet(sheetName)
.doWrite(items);
}
标签:WriteCellStyle,Java,楷体,EasyExcel,contentFont,字体,new,headFont From: https://blog.csdn.net/zhaoyaxuan001/article/details/141226001