EasyExcel 是阿里巴巴的一个基于Java的简单方便省内存的读写Excel开源项目。

常用方法,见官方文档:https://easyexcel.opensource.alibaba.com/docs/current/   

下面介绍,Alibaba EasyExcel:通用批量设置 标题头样式(背景色,字体等)、内容表体样式(背景色、字体、边框等)版本 2.2.6+   


当我们的标题头,与内容数据,的样式基本统一时,可以使用此方法方便的统一管理Excel样式。

com.alibaba.excel.write.style.HorizontalCellStyleStrategy   


一、首先设置头样式:

WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());// 背景设置
WriteFont headWriteFont = new WriteFont();
headWriteFont.setFontHeightInPoints((short)16);// 字体大小
headWriteCellStyle.setWriteFont(headWriteFont);


二、接着设置 内容样式:

WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
// 这里需要指定 FillPatternType 为 FillPatternType.SOLID_FOREGROUND,才会显示背景色
contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
// 背景绿色
contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
WriteFont contentWriteFont = new WriteFont();
// 字体大小
contentWriteFont.setFontHeightInPoints((short)20);
contentWriteCellStyle.setWriteFont(contentWriteFont);
// 边框
contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);//细实线
contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);


三、通过 HorizontalCellStyleStrategy 合并 头与体样式:

HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

四、通过 ExcelWriterBuilder 对象 registerWriteHandler 方法注册样式操作:

response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("学生列表", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(response.getOutputStream());
excelWriterBuilder.registerWriteHandler(horizontalCellStyleStrategy);
ExcelWriter excelWriter = excelWriterBuilder.build();


五、创建 Sheet 构建Excel文件:

ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.writerSheet(0, "学生列表");
WriteSheet writeSheet = excelWriterSheetBuilder.head(head).build();// head 是一个二维数组,来表示头
excelWriter.write(data, writeSheet);// data 为数据
excelWriter.finish();// 记录一定要finish






点赞(0) 打赏

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部