1. EasyExcel简介

EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。 github地址: https://github.com/alibaba/easyexcel

2. 使用方法

添加依赖
        <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.11</version></dependency>
设置excel默认样式
public static HorizontalCellStyleStrategy defaultStyles() {//TODO 默认样式//表头样式策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();//设置表头居中对齐headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//表头前景设置淡蓝色headWriteCellStyle.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());WriteFont headWriteFont = new WriteFont();headWriteFont.setBold(true);headWriteFont.setFontName("宋体");headWriteFont.setFontHeightInPoints((short) 12);headWriteCellStyle.setWriteFont(headWriteFont);//内容样式策略策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 设置背景颜色白色contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());// 设置垂直居中为居中对齐contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置左右对齐为靠左对齐contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);// 设置单元格上下左右边框为细边框contentWriteCellStyle.setBorderBottom(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderLeft(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderRight(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderTop(BorderStyle.MEDIUM);//创建字体对象WriteFont contentWriteFont = new WriteFont();//内容字体大小contentWriteFont.setFontName("宋体");contentWriteFont.setFontHeightInPoints((short) 14);contentWriteCellStyle.setWriteFont(contentWriteFont);// 初始化表格样式HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);return horizontalCellStyleStrategy;}
自定义单元格样式
package com.james.easy.excel.demo.utils;import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.StyleUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.*;import java.util.HashMap;
import java.util.List;/*** @author james* @version 1.0* @description: 设置单元格格式* @date 2021/10/16 15:46*/
public class CellColorSheetWriteHandler implements CellWriteHandler {/*** map* key:第i行* value:第i行中单元格索引集合*/private HashMap<Integer, List<Integer>> map;/*** 颜色*/private Short colorIndex;/*** 有参构造*/public CellColorSheetWriteHandler(HashMap<Integer, List<Integer>> map, Short colorIndex) {this.map = map;this.colorIndex = colorIndex;}/*** 无参构造*/public CellColorSheetWriteHandler() {}/*** 在创建单元格之前调用*/@Overridepublic void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {}/*** 在单元格创建后调用*/@Overridepublic void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}@Overridepublic void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, CellData cellData, Cell cell, Head head, Integer integer, Boolean aBoolean) {}/*** 在单元上的所有操作完成后调用*/@Overridepublic void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {Sheet sheet = writeSheetHolder.getSheet();/*** 考虑到导出数据量过大的情况,不对每一行的每一个单元格进行样式设置,只设置必要行中的某个单元格的样式*///当前行的第i列int i = cell.getColumnIndex();//不处理第一行if (0 != cell.getRowIndex()) {List<Integer> integers = map.get(cell.getRowIndex());if (integers != null && integers.size() > 0) {if (integers.contains(i)) {// 根据单元格获取workbookWorkbook workbook = cell.getSheet().getWorkbook();//设置行高writeSheetHolder.getSheet().getRow(cell.getRowIndex()).setHeight((short) (1.4 * 256));writeSheetHolder.getSheet().setDefaultColumnWidth(200);// 单元格策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 设置背景颜色白色contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());// 设置垂直居中为居中对齐contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 设置左右对齐为靠左对齐contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);// 设置单元格上下左右边框为细边框contentWriteCellStyle.setBorderBottom(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderLeft(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderRight(BorderStyle.MEDIUM);contentWriteCellStyle.setBorderTop(BorderStyle.MEDIUM);// 创建字体实例WriteFont cellWriteFont = new WriteFont();// 设置字体大小cellWriteFont.setFontName("宋体");cellWriteFont.setFontHeightInPoints((short) 14);//设置字体颜色cellWriteFont.setColor(colorIndex);//单元格颜色contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());contentWriteCellStyle.setWriteFont(cellWriteFont);CellStyle cellStyle = StyleUtil.buildHeadCellStyle(workbook, contentWriteCellStyle);//设置当前行第i列的样式cell.getRow().getCell(i).setCellStyle(cellStyle);}}}}}
设置导出列的自适应宽度
package com.james.easy.excel.demo.utils;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** @author james* @version 1.0* @description: 导出列的自适应宽度* @date 2021/10/16 17:12*/public class CustomCellWriteHandler extends AbstractColumnWidthStyleStrategy {private static final int MAX_COLUMN_WIDTH = 255;private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);public CustomCellWriteHandler() {}@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap(16);CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(cellDataList, cell, isHead);if (columnWidth >= 0) {if (columnWidth > 255) {columnWidth = 255;}Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);}}}}private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = (CellData)cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch(type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}
}
生成excel
    /*** 生成excel* @param excelName excel名称* @param sheetName excel sheet名称* @param bodyList excel 主数据* @param headList excel 头标题*/public void generateExcel(String excelName, String sheetName, List<List<String>> bodyList, List<List<String>> headList) {HorizontalCellStyleStrategy horizontalCellStyleStrategy = defaultStyles();CustomCellWriteHandler handler = new CustomCellWriteHandler();//指定单元格样式//用来记录需要为第`key`行中的第`value.get(i)`列设置样式HashMap<Integer, List<Integer>> map = new HashMap<>();CellColorSheetWriteHandler writeHandler = new CellColorSheetWriteHandler(map, IndexedColors.RED.getIndex());EasyExcel.write(excelName + ".xlsx").excelType(ExcelTypeEnum.XLSX).sheet().sheetName(sheetName).head(headList).automaticMergeHead(true).registerWriteHandler(horizontalCellStyleStrategy).registerWriteHandler(writeHandler).registerWriteHandler(handler).doWrite(bodyList);}
测试
    public static void main(String[] args) {EasyExcelUtil util = new EasyExcelUtil();// excel 表数据List<List<String>> bodyList = new ArrayList<>();// excel 表头List<List<String>> headList = new ArrayList<>();String[] headerName = {"test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8"};for (int i = 0; i < headerName.length; i++) {List<String> list = new ArrayList<>();list.add(headerName[i]);headList.add(list);}List<String> list = new ArrayList<>();List<String> list1 = new ArrayList<>();List<String> list2 = new ArrayList<>();list.add("1");list.add("2");list.add("3");list.add("4");list1.add("5");list1.add("6");list1.add("7");list1.add("8");list2.add("1");list2.add("9");list2.add("30");list2.add("40");bodyList.add(list1);bodyList.add(list);bodyList.add(list2);util.generateExcel(DateUtil.now(), "sheet", bodyList, headList);}

使用Easyexcel动态生成excel相关推荐

  1. word文档中动态生成excel表格(基金公告系列讲解)

    1.本博文仅为了将之前工作中动态生成XBRL文件需求中word文档动态生成excel部分进行了实现(虽然隔着时间比较久),闲暇之余的考虑,应对大批量文件生成时可采用定时任务+多线程技术+redis队列 ...

  2. Java动态生成excel模板文件(包含列下拉)

    1.添加依赖 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency><gr ...

  3. EasyExcel 快速生成Excel工具的使用

    EasyExcel 快速生成Excel工具的使用 前言 当我从数据库查询到数据,如何将它变成Excel表格的形式展示 一个简单的导出模板如下 导入依赖 <!-- easyexcel-->& ...

  4. vue + xlsx 动态生成Excel,合并单元格

    根据数据动态生成一个Excel导出文件,这个公共相对简单一些,引入 xlsx就可以了. 但是根据需求,动态合并单元格,貌似难度不小,这里需要对 xlsx的属性和方法有一定的了解才可以,那么一起学习一下 ...

  5. JAVA动态生成excel模板;列自定义下拉框赋值

    哈喽,2023大家开工大吉啊!财源滚滚! 业务需求:需要生成excel模板,且对部分列设置下拉框,进行动态赋值,效果如下: 拿上图举例:针对省这一列,不是填写,而是选择数据,也就是说我们生成excel ...

  6. java动态生成excel_java动态生成excel打包下载

    @SuppressWarnings("unchecked")public String batchExport() throwsDBException{ @SuppressWarn ...

  7. 根据excel列动态创建mysql表_根据数据库字段动态生成excel模版下载,上传模版获取数据存入数据库(poi 反射)...

    环境:mysql5.7.28 java8 Spring boot 2.2.4 mybatis-plus3.10 动态:根据需求,用户可以选择对应的字段生成excle模版 下载 poi 反射:poi是e ...

  8. easyExcel动态生成表头

    之前的都是固定格式处理excel,这次是动态的导出excel,下边是处理表头的,主要就是把表头放到headList List<List<Object>> list = new ...

  9. js 根据树结构动态生成excel表头参数

    代码片段如下 const sheetHead = [{id: 'ee',pid: 'root',label: '日期',prop: 'date'},{id: 'ww',pid: 'root',labe ...

最新文章

  1. Python for虚幻引擎编辑器工具脚本学习教程
  2. jquery动态添加元素无法触发绑定事件的解决方案。
  3. Android之Xposed框架完全使用指南
  4. Git之变基方式Rebase的使用
  5. 教你怎么上传本地代码到github
  6. 图片上添加文字--div
  7. 死锁问题分析(个人认为重点讲到了gap间隙锁,解决了我一些不明报死锁的问题)
  8. 面向对象编程,设计原则,设计模式
  9. Object强转为实体类类型失败!!!!!!
  10. 等级保护三级备案材料有哪些
  11. 关于c# naudio的几个注意事项
  12. 新科LoRa网关和LoRa节点
  13. 联想硬盘保护系统 计算机名 后缀,联想硬盘保护7.07.6安装及计算机名相同的解决方法...
  14. 手机输入法带拼音声调_五笔已经淘汰,拼音到达瓶颈,百度重拳出击,全新输入方式来袭!...
  15. sql计算字段中字数的个数
  16. UINO优锘:用悬疑舞台剧的方式打开3D开发工程师的一天
  17. (zz)楚王何故好细腰
  18. bearer token_接口认证方式:Bearer Token
  19. LL(1)语法分析实验报告
  20. AVG神作是如何炼成的? 《逆转裁判》成步堂三部曲解析

热门文章

  1. CSDN花里胡哨的自定义模板
  2. mysql 同步失败_mysql 同步失败解决方法 (错误:1236)
  3. sw转cad映射文件_SW转CAD完美无乱码教程 附JPG PDF SW CAD格式转换工具
  4. Day 236/300 mac 微信能连接上网 浏览器无法使用
  5. spi遵循_我今天将遵循样式指南
  6. js 秒数转换成时分
  7. java 面向接口编程
  8. RTSP服务器(二)
  9. IIC不能连续读出多个字节
  10. SQL注入Update注入