public HorizontalCellStyleStrategy excelStyle() {
// 头的策略
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
WriteFont headWriteFont = new WriteFont();
// 设置字体大小
headWriteFont.setFontHeightInPoints((short) 11);
// 设置字体名字
headWriteFont.setFontName("Calibri");
// 在样式用应用设置的字体
headWriteCellStyle.setWriteFont(headWriteFont);
// 设置自动换行
headWriteCellStyle.setWrapped(false);
// 设置水平对齐的样式为居中对齐
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
// 设置垂直对齐的样式为居中对齐
headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 内容的策略
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 字体策略
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short) 11);
// 设置字体名字
contentWriteFont.setFontName("Calibri");
// 在样式用应用设置的字体
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 设置自动换行
contentWriteCellStyle.setWrapped(false);
//设置垂直对齐的样式为居中对齐
contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
//设置水平对齐的样式为居中对齐
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
}
ExcelWriter excelWriter = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
HorizontalCellStyleStrategy styleStrategy = this.excelStyle();
excelWriter = EasyExcel.write(out)
.excelType(ExcelTypeEnum.XLSX)
.registerWriteHandler(styleStrategy)
.build();
WriteSheet writeSheet = EasyExcel.writerSheet().build();
excelWriter.write(dataList, writeSheet);
excelWriter.finish();
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new RuntimeException("Export excel failed.", e);
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
}
@ColumnWidth 设置列宽
@ExcelProperty 设置列头