一、引入依赖

<!-- easyexcel 该版本已解决数值精度丢失问题-->
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.10</version>
</dependency>

二、常用注解介绍

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "Test 测试表 DTO")
@ContentRowHeight(20) // 内容行高
@HeadRowHeight(40) // 标题行高
@ColumnWidth(25) // 全局列宽,某个字段需要特异化,可以在字段上声明
public class TestDTO {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "主键", example = "111")// @ExcelIgnore // 忽略该列,不展示@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40) //内容样式设置@ExcelProperty(value = "主键", index = 2) // 该字段为第1列,列名为主键private String id;@ApiModelProperty(value = "用户名", example = "zhangsan", required = true)@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40) // 标题样式设置// @ExcelProperty(value = "用户名", index = 0)@ExcelProperty(value = {"主标题", "用户名"}, index = 1)  // 该字段为第2列,一级标题为主标题,二级标题为用户名private String username;@ApiModelProperty(value = "密码", example = "123456")// @ExcelProperty(value = "密码", index = 2)@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)@ExcelProperty(value = {"主标题", "密码"}, index = 0)// 该字段为第3列,一级标题为主标题,二级标题为密码@ColumnWidth(50) // 该字段列宽@Sensitive(type = SensitiveTypeEnum.CUSTOMER, prefixNoMaskLen = 2, suffixNoMaskLen = 3, maskStr = "*")private String password;}

三、自定义样式信息类(某一单元格特定样式时使用)

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFColor;/*** 样式信息类** @author author* @date 2022/6/21*/
@Data
public class ExcelCellStyleModel {/*** sheet名称*/private String sheetName;/*** 列索引*/private int colIndex;/*** 行索引*/private int rowIndex;/*** 字体名称*/private String fontName;/*** 字体大小*/private Double fontHeight;/*** 字体颜色*/private Object fontColor;/*** 字体加粗*/private Boolean fontBold;/*** 字体斜体*/private Boolean fontItalic;/*** 字体下划线*/private Byte fontUnderLine;/*** 字体上标下标*/private Short fontTypeOffset;/*** 字体删除线*/private Boolean fontStrikeout;/*** 背景颜色*/private Object backgroundColor;/*** 上边框线条类型*/private BorderStyle borderTop;/*** 右边框线条类型*/private BorderStyle borderRight;/*** 下边框线条类型*/private BorderStyle borderBottom;/*** 左边框线条类型*/private BorderStyle borderLeft;/*** 上边框线条颜色*/private Object topBorderColor;/*** 上边框线条颜色*/private Object rightBorderColor;/*** 下边框线条颜色*/private Object bottomBorderColor;/****/private Object leftBorderColor;/*** 水平对齐方式*/private HorizontalAlignment horizontalAlignment;/*** 垂直对齐方式*/private VerticalAlignment verticalAlignment;/*** 自动换行方式*/private Boolean wrapText;/*** 生成字体名称样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param fontName    字体名称(默认宋体)* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontNameCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, fontName, null, null, null, null, null, null, null);}/*** 生成字体名称大小信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param fontHeight  字体大小* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontHeightCellStyleModel(String sheetName, int rowIndex, int columnIndex, Double fontHeight) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, fontHeight, null, null, null, null, null, null);}/*** 得到RGB自定义颜色** @param redNum   红色数值* @param greenNum 绿色数值* @param blueNum  蓝色数值* @return org.apache.poi.xssf.usermodel.XSSFColor*/public static XSSFColor getRGBColor(int redNum, int greenNum, int blueNum) {return new XSSFColor(new byte[]{(byte) redNum, (byte) greenNum, (byte) blueNum}, new DefaultIndexedColorMap());}/*** 生成字体颜色样式信息(支持自定义RGB颜色)** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param redNum      红色数值* @param greenNum    绿色数值* @param blueNum     蓝色数值* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, int redNum, int greenNum, int blueNum) {XSSFColor fontColor = getRGBColor(redNum, greenNum, blueNum);return createFontColorCellStyleModel(sheetName, rowIndex, columnIndex, fontColor);}/*** 生成字体颜色样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param fontColor   字体颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object fontColor) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, fontColor, null, null, null, null, null);}/*** 生成字体加粗样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param fontBold    字体加粗* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontBoldCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontBold) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, fontBold, null, null, null, null);}/*** 生成字体斜体样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param fontItalic  字体斜体* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontItalicCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontItalic) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, fontItalic, null, null, null);}/*** 生成字体下划线样式信息** @param sheetName     sheet页名称* @param rowIndex      行号* @param columnIndex   列号* @param fontUnderLine 字体下划线* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontUnderLineCellStyleModel(String sheetName, int rowIndex, int columnIndex, Byte fontUnderLine) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, fontUnderLine, null, null);}/*** 生成字体上标下标样式信息** @param sheetName      sheet页名称* @param rowIndex       行号* @param columnIndex    列号* @param fontTypeOffset 字体上标下标* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontTypeOffsetCellStyleModel(String sheetName, int rowIndex, int columnIndex, Short fontTypeOffset) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, fontTypeOffset, null);}/*** 生成字体删除线样式信息** @param sheetName     sheet页名称* @param rowIndex      行号* @param columnIndex   列号* @param fontStrikeout 字体删除线* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontStrikeoutCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean fontStrikeout) {return createFontCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, fontStrikeout);}/*** 生成字体样式信息** @param sheetName      sheet页名称* @param rowIndex       行号* @param columnIndex    列号* @param fontName       字体名称(默认宋体)* @param fontHeight     字体大小* @param fontColor      字体颜色* @param fontBold       字体加粗* @param fontItalic     字体斜体* @param fontUnderLine  字体下划线* @param fontTypeOffset 字体上标下标* @param fontStrikeout  字体删除线* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createFontCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine, Short fontTypeOffset, Boolean fontStrikeout) {return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic, fontUnderLine, fontTypeOffset, fontStrikeout, null);}/*** 生成背景颜色样式信息** @param sheetName       sheet页名称* @param rowIndex        行号* @param columnIndex     列号* @param backgroundColor 背景颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBackgroundColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object backgroundColor) {return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null, backgroundColor);}/*** 生成背景颜色样式信息(支持自定义RGB颜色)** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param redNum      红色数值* @param greenNum    绿色数值* @param blueNum     蓝色数值* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBackgroundColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, int redNum, int greenNum, int blueNum) {XSSFColor backgroundColor = getRGBColor(redNum, greenNum, blueNum);return createBackgroundColorCellStyleModel(sheetName, rowIndex, columnIndex, backgroundColor);}/*** 生成样式信息** @param sheetName       sheet页名称* @param rowIndex        行号* @param columnIndex     列号* @param fontName        字体名称(宋体)* @param fontHeight      字体大小* @param fontColor       字体颜色* @param fontBold        字体加粗* @param fontItalic      字体斜体* @param fontUnderLine   字体下划线* @param fontTypeOffset  字体上标下标* @param fontStrikeout   字体删除线* @param backgroundColor 背景颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine, Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor) {return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic, fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, null, null, null, null, null, null, null, null);}/*** 生成上边框线条颜色样式信息** @param sheetName      sheet页名称* @param rowIndex       行号* @param columnIndex    列号* @param topBorderColor 上边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createTopBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object topBorderColor) {return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, topBorderColor, null, null, null);}/*** 生成右边框线条颜色样式信息** @param sheetName        sheet页名称* @param rowIndex         行号* @param columnIndex      列号* @param rightBorderColor 右边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createRightBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object rightBorderColor) {return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, rightBorderColor, null, null);}/*** 生成下边框线条颜色样式信息** @param sheetName         sheet页名称* @param rowIndex          行号* @param columnIndex       列号* @param bottomBorderColor 下边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBottomBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object bottomBorderColor) {return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, null, bottomBorderColor, null);}/*** 生成左边框线条颜色样式信息** @param sheetName       sheet页名称* @param rowIndex        行号* @param columnIndex     列号* @param leftBorderColor 左边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createLeftBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object leftBorderColor) {return createBorderColorCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, leftBorderColor);}/*** 生成上边框线条类型样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param borderTop   上边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createTopBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderTop) {return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, borderTop, null, null, null);}/*** 生成右边框线条类型样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param borderRight 右边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createRightBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderRight) {return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, borderRight, null, null);}/*** 生成下边框线条类型样式信息** @param sheetName    sheet页名称* @param rowIndex     行号* @param columnIndex  列号* @param borderBottom 下边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBottomBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderBottom) {return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, null, borderBottom, null);}/*** 生成左边框线条类型样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param borderLeft  左边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createLeftBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderLeft) {return createBorderLineTypeCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, borderLeft);}/*** 生成边框线条颜色样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param borderColor 边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object borderColor) {return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, null, borderColor);}/*** 生成边框线条颜色样式信息** @param sheetName         sheet页名称* @param rowIndex          行号* @param columnIndex       列号* @param topBorderColor    上边框线条颜色* @param rightBorderColor  右边框线条颜色* @param bottomBorderColor 下边框线条颜色* @param leftBorderColor   左边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderColorCellStyleModel(String sheetName, int rowIndex, int columnIndex, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor) {return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor);}/*** 生成边框线条类型样式信息** @param sheetName      sheet页名称* @param rowIndex       行号* @param columnIndex    列号* @param borderLineType 边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderLineType) {return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderLineType, null);}/*** 生成边框线条类型样式信息** @param sheetName    sheet页名称* @param rowIndex     行号* @param columnIndex  列号* @param borderTop    上边框线条类型* @param borderRight  右边框线条类型* @param borderBottom 下边框线条类型* @param borderLeft   左边框线条类型* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderLineTypeCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft) {return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderTop, borderRight, borderBottom, borderLeft, null, null, null, null);}/*** 生成边框样式信息** @param sheetName      sheet页名称* @param rowIndex       行号* @param columnIndex    列号* @param borderLineType 边框线条类型* @param borderColor    边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderLineType, Object borderColor) {return createBorderCellStyleModel(sheetName, rowIndex, columnIndex, borderLineType, borderLineType, borderLineType, borderLineType, borderColor, borderColor, borderColor, borderColor);}/*** 生成边框样式信息** @param sheetName         sheet页名称* @param rowIndex          行号* @param columnIndex       列号* @param borderTop         上边框线条类型* @param borderRight       右边框线条类型* @param borderBottom      下边框线条类型* @param borderLeft        左边框线条类型* @param topBorderColor    上边框线条颜色* @param rightBorderColor  右边框线条颜色* @param bottomBorderColor 下边框线条颜色* @param leftBorderColor   左边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createBorderCellStyleModel(String sheetName, int rowIndex, int columnIndex, BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor) {return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null, null, borderTop, borderRight, borderBottom, borderLeft, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor);}/*** 生成样式信息** @param sheetName         sheet页名称* @param rowIndex          行号* @param columnIndex       列号* @param fontName          字体名称(宋体)* @param fontHeight        字体大小* @param fontColor         字体颜色* @param fontBold          字体加粗* @param fontItalic        字体斜体* @param fontUnderLine     字体下划线* @param fontTypeOffset    字体上标下标* @param fontStrikeout     字体删除线* @param backgroundColor   背景颜色* @param borderTop         上边框线条类型* @param borderRight       右边框线条类型* @param borderBottom      下边框线条类型* @param borderLeft        左边框线条类型* @param topBorderColor    上边框线条颜色* @param rightBorderColor  右边框线条颜色* @param bottomBorderColor 下边框线条颜色* @param leftBorderColor   左边框线条颜色* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine, Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor) {return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic, fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, borderTop, borderRight, borderBottom, borderLeft, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor, null, null);}/*** 生成水平对齐方式信息** @param sheetName           sheet页名称* @param rowIndex            行号* @param columnIndex         列号* @param horizontalAlignment 水平对齐方式* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createHorizontalAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex, HorizontalAlignment horizontalAlignment) {return createAlignmentCellStyleModel(sheetName, rowIndex, columnIndex, horizontalAlignment, null);}/*** 生成垂直对齐方式信息** @param sheetName         sheet页名称* @param rowIndex          行号* @param columnIndex       列号* @param verticalAlignment 垂直对齐方式* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createVerticalAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex, VerticalAlignment verticalAlignment) {return createAlignmentCellStyleModel(sheetName, rowIndex, columnIndex, null, verticalAlignment);}/*** 生成对齐方式信息** @param sheetName           sheet页名称* @param rowIndex            行号* @param columnIndex         列号* @param horizontalAlignment 水平对齐方式* @param verticalAlignment   垂直对齐方式* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createAlignmentCellStyleModel(String sheetName, int rowIndex, int columnIndex, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, horizontalAlignment, verticalAlignment);}/*** 生成样式信息** @param sheetName           sheet页名称* @param rowIndex            行号* @param columnIndex         列号* @param fontName            字体名称(宋体)* @param fontHeight          字体大小* @param fontColor           字体颜色* @param fontBold            字体加粗* @param fontItalic          字体斜体* @param fontUnderLine       字体下划线* @param fontTypeOffset      字体上标下标* @param fontStrikeout       字体删除线* @param backgroundColor     背景颜色* @param borderTop           上边框线条类型* @param borderRight         右边框线条类型* @param borderBottom        下边框线条类型* @param borderLeft          左边框线条类型* @param topBorderColor      上边框线条颜色* @param rightBorderColor    右边框线条颜色* @param bottomBorderColor   下边框线条颜色* @param leftBorderColor     左边框线条颜色* @param horizontalAlignment 水平对齐方式* @param verticalAlignment   垂直对齐方式* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine, Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) {return createCellStyleModel(sheetName, rowIndex, columnIndex, fontName, fontHeight, fontColor, fontBold, fontItalic, fontUnderLine, fontTypeOffset, fontStrikeout, backgroundColor, borderTop, borderRight, borderBottom, borderLeft, topBorderColor, rightBorderColor, bottomBorderColor, leftBorderColor, horizontalAlignment, verticalAlignment, null);}/*** 生成自动换行样式信息** @param sheetName   sheet页名称* @param rowIndex    行号* @param columnIndex 列号* @param wrapText    自动换行* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createWrapTextCellStyleModel(String sheetName, int rowIndex, int columnIndex, Boolean wrapText) {return createCellStyleModel(sheetName, rowIndex, columnIndex, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, wrapText);}/*** 生成样式信息** @param sheetName           sheet页名称* @param rowIndex            行号* @param columnIndex         列号* @param fontName            字体名称(宋体)* @param fontHeight          字体大小* @param fontColor           字体颜色* @param fontBold            字体加粗* @param fontItalic          字体斜体* @param fontUnderLine       字体下划线* @param fontTypeOffset      字体上标下标* @param fontStrikeout       字体删除线* @param backgroundColor     背景颜色* @param borderTop           上边框线条类型* @param borderRight         右边框线条类型* @param borderBottom        下边框线条类型* @param borderLeft          左边框线条类型* @param topBorderColor      上边框线条颜色* @param rightBorderColor    右边框线条颜色* @param bottomBorderColor   下边框线条颜色* @param leftBorderColor     左边框线条颜色* @param horizontalAlignment 水平对齐方式* @param verticalAlignment   垂直对齐方式* @param wrapText            自动换行* @return com.hft.nbp.common.core.model.ExcelCellStyleModel*/public static ExcelCellStyleModel createCellStyleModel(String sheetName, int rowIndex, int columnIndex, String fontName, Double fontHeight, Object fontColor, Boolean fontBold, Boolean fontItalic, Byte fontUnderLine, Short fontTypeOffset, Boolean fontStrikeout, Object backgroundColor, BorderStyle borderTop, BorderStyle borderRight, BorderStyle borderBottom, BorderStyle borderLeft, Object topBorderColor, Object rightBorderColor, Object bottomBorderColor, Object leftBorderColor, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment, Boolean wrapText) {ExcelCellStyleModel excelCellStyleModel = new ExcelCellStyleModel();//sheet页名称excelCellStyleModel.setSheetName(sheetName);//行号excelCellStyleModel.setRowIndex(rowIndex);//列号excelCellStyleModel.setColIndex(columnIndex);//设置字体样式//字体名称(比如宋体)fontName = fontName != null && StrUtil.equals(fontName, "") ? "宋体" : fontName;excelCellStyleModel.setFontName(fontName);//字体大小fontHeight = fontHeight != null && fontHeight <= 0 ? null : fontHeight;excelCellStyleModel.setFontHeight(fontHeight);//字体颜色fontColor = fontColor != null && (!(fontColor instanceof IndexedColors) && !(fontColor instanceof XSSFColor))? null : fontColor;excelCellStyleModel.setFontColor(fontColor);//字体加粗excelCellStyleModel.setFontBold(fontBold);//字体斜体excelCellStyleModel.setFontItalic(fontItalic);//字体下划线fontUnderLine = fontUnderLine != null && (fontUnderLine != Font.U_NONE && fontUnderLine != Font.U_SINGLE && fontUnderLine != Font.U_DOUBLE&& fontUnderLine != Font.U_DOUBLE_ACCOUNTING && fontUnderLine != Font.U_SINGLE_ACCOUNTING) ? null : fontUnderLine;excelCellStyleModel.setFontUnderLine(fontUnderLine);//字体上标下标fontTypeOffset = fontTypeOffset != null && (fontTypeOffset != Font.SS_NONE && fontTypeOffset != Font.SS_SUB && fontTypeOffset != Font.SS_SUPER)? null : fontTypeOffset;excelCellStyleModel.setFontTypeOffset(fontTypeOffset);//字体删除线excelCellStyleModel.setFontStrikeout(fontStrikeout);//背景颜色backgroundColor = backgroundColor != null && (!(backgroundColor instanceof IndexedColors) && !(backgroundColor instanceof XSSFColor))? null : backgroundColor;excelCellStyleModel.setBackgroundColor(backgroundColor);//边框样式//上边框线条类型excelCellStyleModel.setBorderTop(borderTop);//右边框线条类型excelCellStyleModel.setBorderRight(borderRight);//下边框线条类型excelCellStyleModel.setBorderBottom(borderBottom);//左边框线条类型excelCellStyleModel.setBorderLeft(borderLeft);//上边框颜色类型excelCellStyleModel.setTopBorderColor(topBorderColor);//右边框颜色类型excelCellStyleModel.setRightBorderColor(rightBorderColor);//下边框颜色类型excelCellStyleModel.setBottomBorderColor(bottomBorderColor);//左边框颜色类型excelCellStyleModel.setLeftBorderColor(leftBorderColor);//对齐方式//水平对齐方式excelCellStyleModel.setHorizontalAlignment(horizontalAlignment);//垂直对齐方式excelCellStyleModel.setVerticalAlignment(verticalAlignment);//自动换行excelCellStyleModel.setWrapText(wrapText);return excelCellStyleModel;}
}

四、自定义单元格样式处理器(某一单元格特定样式时使用)

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.hft.nbp.common.core.model.ExcelCellStyleModel;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.springframework.util.CollectionUtils;import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;/*** 自定义单元格样式处理器(支持字体样式、背景颜色、边框样式、对齐方式、自动换行)** @author author* @date 2022/6/21*/
public class ExcelCellStyleHandler extends AbstractRowWriteHandler {/*** sheet页名称列表*/private List<String> sheetNameList;/*** 样式信息*/private List<ExcelCellStyleModel> cellStyleList = new ArrayList<>();/*** 自定义样式适配器构造方法** @param cellStyleList 样式信息*/public ExcelCellStyleHandler(List<ExcelCellStyleModel> cellStyleList) {if (CollectionUtil.isEmpty(cellStyleList)) {return;}cellStyleList = cellStyleList.stream().filter(x -> x != null//判断sheet名称KEY是否存在&& StrUtil.isNotBlank(x.getSheetName())//字体样式//判断字体颜色KEY是否存在&& (x.getFontColor() == null || x.getFontColor() instanceof IndexedColors|| x.getFontColor() instanceof XSSFColor)//判断背景颜色KEY是否存在&& (x.getBackgroundColor() == null || x.getBackgroundColor() instanceof IndexedColors|| x.getBackgroundColor() instanceof XSSFColor)//边框样式// 判断上边框线条颜色KEY是否存在&& (x.getTopBorderColor() == null || x.getTopBorderColor() instanceof IndexedColors|| x.getTopBorderColor() instanceof XSSFColor)// 判断右边框线条颜色KEY是否存在&& (x.getRightBorderColor() == null || x.getRightBorderColor() instanceof IndexedColors|| x.getRightBorderColor() instanceof XSSFColor)// 判断下边框线条颜色KEY是否存在&& (x.getBottomBorderColor() == null || x.getBottomBorderColor() instanceof IndexedColors|| x.getBottomBorderColor() instanceof XSSFColor)// 判断左边框线条颜色KEY是否存在&& (x.getLeftBorderColor() == null || x.getLeftBorderColor() instanceof IndexedColors|| x.getLeftBorderColor() instanceof XSSFColor)).collect(Collectors.toList());this.cellStyleList = cellStyleList;sheetNameList = this.cellStyleList.stream().map(ExcelCellStyleModel::getSheetName).distinct().collect(Collectors.toList());}@Overridepublic void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {if (isHead) {// 跳过表头return;}Sheet sheet = writeSheetHolder.getSheet();//不需要添加样式,或者当前sheet页不需要添加样式if (cellStyleList == null || cellStyleList.size() <= 0 || !sheetNameList.contains(sheet.getSheetName())) {return;}//获取当前行的样式信息List<ExcelCellStyleModel> rowCellStyleList = cellStyleList.stream().filter(x ->StrUtil.equals(x.getSheetName(), sheet.getSheetName()) && x.getRowIndex() == relativeRowIndex).collect(Collectors.toList());//该行不需要设置样式if (CollectionUtils.isEmpty(rowCellStyleList)) {return;}for (ExcelCellStyleModel excelCellStyleModel : rowCellStyleList) {//设置单元格样式setCellStyle(excelCellStyleModel, row);}//删除已添加的样式信息cellStyleList.removeAll(rowCellStyleList);//重新获取要添加的sheet页姓名sheetNameList = cellStyleList.stream().map(ExcelCellStyleModel::getSheetName).distinct().collect(Collectors.toList());}/*** 给单元格设置样式** @param excelCellStyleModel 样式信息* @param row                 行对象*/private void setCellStyle(ExcelCellStyleModel excelCellStyleModel, Row row) {//背景颜色Object backgroundColor = excelCellStyleModel.getBackgroundColor();//自动换行Boolean wrapText = excelCellStyleModel.getWrapText();//列索引int colIndex = excelCellStyleModel.getColIndex();//边框样式Cell cell = row.getCell(colIndex);if (cell == null) {cell = row.createCell(colIndex);}XSSFCellStyle style = (XSSFCellStyle) cell.getRow().getSheet().getWorkbook().createCellStyle();// 克隆出一个 stylestyle.cloneStyleFrom(cell.getCellStyle());//设置背景颜色if (backgroundColor != null) {//使用IndexedColors定义的颜色if (backgroundColor instanceof IndexedColors) {style.setFillForegroundColor(((IndexedColors) backgroundColor).getIndex());}//使用自定义的RGB颜色else if (backgroundColor instanceof XSSFColor) {style.setFillForegroundColor((XSSFColor) backgroundColor);}style.setFillPattern(FillPatternType.SOLID_FOREGROUND);}//设置自动换行if (wrapText != null) {style.setWrapText(wrapText);}//设置字体样式setFontStyle(row, style, excelCellStyleModel);//设置边框样式setBorderStyle(style, excelCellStyleModel);//设置对齐方式setAlignmentStyle(style, excelCellStyleModel);cell.setCellStyle(style);}/*** 设置字体样式** @param row                 行对象* @param style               单元格样式* @param excelCellStyleModel 样式信息*/private void setFontStyle(Row row, XSSFCellStyle style, ExcelCellStyleModel excelCellStyleModel) {//字体名称String fontName = excelCellStyleModel.getFontName();//字体大小Double fontHeight = excelCellStyleModel.getFontHeight();//字体颜色Object fontColor = excelCellStyleModel.getFontColor();//字体加粗Boolean fontBold = excelCellStyleModel.getFontBold();//字体斜体Boolean fontItalic = excelCellStyleModel.getFontItalic();//字体下划线Byte fontUnderLine = excelCellStyleModel.getFontUnderLine();//字体上标下标Short fontTypeOffset = excelCellStyleModel.getFontTypeOffset();//字体删除线Boolean fontStrikeout = excelCellStyleModel.getFontStrikeout();//不需要设置字体样式if (fontName == null && fontHeight == null && fontColor == null && fontBold == null && fontItalic == null&& fontUnderLine == null && fontTypeOffset == null && fontStrikeout == null) {return;}XSSFFont font;//样式存在字体对象时,使用原有的字体对象if (style.getFontIndex() != 0) {font = style.getFont();}//样式不存在字体对象时,创建字体对象else {font = (XSSFFont) row.getSheet().getWorkbook().createFont();//默认字体为宋体font.setFontName("宋体");}//设置字体名称if (fontName != null) {font.setFontName(fontName);}//设置字体大小if (fontHeight != null) {font.setFontHeight(fontHeight);}//设置字体颜色if (fontColor != null) {//使用IndexedColors定义的颜色if (fontColor instanceof IndexedColors) {font.setColor(((IndexedColors) fontColor).getIndex());}//使用自定义的RGB颜色else if (fontColor instanceof XSSFColor) {font.setColor((XSSFColor) fontColor);}}//设置字体加粗if (fontBold != null) {font.setBold(fontBold);}//设置字体斜体if (fontItalic != null) {font.setItalic(fontItalic);}//设置字体下划线if (fontUnderLine != null) {font.setUnderline(fontUnderLine);}//设置字体上标下标if (fontTypeOffset != null) {font.setTypeOffset(fontTypeOffset);}//设置字体删除线if (fontStrikeout != null) {font.setStrikeout(fontStrikeout);}style.setFont(font);}/*** 设置边框样式** @param style               单元格样式* @param excelCellStyleModel 样式信息*/private void setBorderStyle(XSSFCellStyle style, ExcelCellStyleModel excelCellStyleModel) {//上边框线条类型BorderStyle borderTop = excelCellStyleModel.getBorderTop();//右边框线条类型BorderStyle borderRight = excelCellStyleModel.getBorderRight();//下边框线条类型BorderStyle borderBottom = excelCellStyleModel.getBorderBottom();//左边框线条类型BorderStyle borderLeft = excelCellStyleModel.getBorderLeft();//上边框颜色类型Object topBorderColor = excelCellStyleModel.getTopBorderColor();//右边框颜色类型Object rightBorderColor = excelCellStyleModel.getRightBorderColor();//下边框颜色类型Object bottomBorderColor = excelCellStyleModel.getBottomBorderColor();//左边框颜色类型Object leftBorderColor = excelCellStyleModel.getLeftBorderColor();//不需要设置边框样式if (borderTop == null && borderRight == null && borderBottom == null && borderLeft == null && topBorderColor == null&& rightBorderColor == null && bottomBorderColor == null && leftBorderColor == null) {return;}//设置上边框线条类型if (borderTop != null) {style.setBorderTop(borderTop);}//设置右边框线条类型if (borderRight != null) {style.setBorderRight(borderRight);}//设置下边框线条类型if (borderBottom != null) {style.setBorderBottom(borderBottom);}//设置左边框线条类型if (borderLeft != null) {style.setBorderLeft(borderLeft);}//设置上边框线条颜色if (topBorderColor != null) {//使用IndexedColors定义的颜色if (topBorderColor instanceof IndexedColors) {style.setTopBorderColor(((IndexedColors) topBorderColor).getIndex());}//使用自定义的RGB颜色else if (topBorderColor instanceof XSSFColor) {style.setTopBorderColor((XSSFColor) topBorderColor);}}//设置右边框线条颜色if (rightBorderColor != null) {//使用IndexedColors定义的颜色if (rightBorderColor instanceof IndexedColors) {style.setRightBorderColor(((IndexedColors) rightBorderColor).getIndex());}//使用自定义的RGB颜色else if (rightBorderColor instanceof XSSFColor) {style.setRightBorderColor((XSSFColor) rightBorderColor);}}//设置下边框线条颜色if (bottomBorderColor != null) {//使用IndexedColors定义的颜色if (bottomBorderColor instanceof IndexedColors) {style.setBottomBorderColor(((IndexedColors) bottomBorderColor).getIndex());}//使用自定义的RGB颜色else if (bottomBorderColor instanceof XSSFColor) {style.setBottomBorderColor((XSSFColor) bottomBorderColor);}}//设置左边框线条颜色if (leftBorderColor != null) {//使用IndexedColors定义的颜色if (leftBorderColor instanceof IndexedColors) {style.setLeftBorderColor(((IndexedColors) leftBorderColor).getIndex());}//使用自定义的RGB颜色else if (topBorderColor instanceof XSSFColor) {style.setLeftBorderColor((XSSFColor) leftBorderColor);}}}/*** 设置对齐方式** @param style               单元格样式* @param excelCellStyleModel 样式信息*/private void setAlignmentStyle(XSSFCellStyle style, ExcelCellStyleModel excelCellStyleModel) {//水平对齐方式HorizontalAlignment horizontalAlignment = excelCellStyleModel.getHorizontalAlignment();//垂直对齐方式VerticalAlignment verticalAlignment = excelCellStyleModel.getVerticalAlignment();//不需要设置对齐方式if (horizontalAlignment == null && verticalAlignment == null) {return;}//设置水平对齐方式if (horizontalAlignment != null) {style.setAlignment(horizontalAlignment);}//设置垂直对齐方式if (verticalAlignment != null) {style.setVerticalAlignment(verticalAlignment);}}
}

五、model定义

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "Test 测试表 DTO")
public class TestDTO {private static final long serialVersionUID = 1L;@ApiModelProperty(value = "主键", example = "111")// @ExcelIgnore // 忽略该列,不展示@ContentStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40) // 内容样式设置@ExcelProperty(value = "主键", index = 2) // 该字段为第1列,列名为主键private String id;@ApiModelProperty(value = "用户名", example = "zhangsan", required = true)@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40) // 标题样式设置// @ExcelProperty(value = "用户名", index = 0)@ExcelProperty(value = {"主标题", "用户名"}, index = 1)  // 该字段为第2列,一级标题为主标题,二级标题为用户名private String username;@ApiModelProperty(value = "密码", example = "123456")// @ExcelProperty(value = "密码", index = 2)@HeadStyle(fillPatternType = FillPatternType.SOLID_FOREGROUND, fillForegroundColor = 40)@ExcelProperty(value = {"主标题", "密码"}, index = 0)// 该字段为第3列,一级标题为主标题,二级标题为密码@ColumnWidth(50) // 该字段列宽@Sensitive(type = SensitiveTypeEnum.CUSTOMER, prefixNoMaskLen = 2, suffixNoMaskLen = 3, maskStr = "*")private String password;
}
@Data
public class Model implements Serializable {/*** 主键*/@TableId@ExcelIgnoreprivate String id;/*** 批量导入日期*/@ExcelIgnoreprivate String batchdate;/*** 基金代码*/@ExcelProperty(value = "基金代码", index = 0)private String fundCode;/*** 基金名称*/@ExcelProperty(value = "基金名称", index = 1)private String fundName;@TableField(exist = false)private static final long serialVersionUID = 1L;
}

六、Excel导出

@ApiOperation(value = "测试自定义Excel文件下载", notes = "测试自定义Excel文件下载")
@SysLog("测试自定义Excel文件下载")
@GetMapping(value = "/customizeDownload")
public void customizeDownload(){TestDTO dto1=new TestDTO("100","张三","张三的密码");TestDTO dto2=new TestDTO("200","李四","李四的密码");// 该集合内容填充至模板一ArrayList<TestDTO> list1 = Lists.newArrayList(dto1, dto2);Model Model1=new Model();Model1.setFundCode("编码1");Model1.setFundName("名称1");Model Model2=new Model();Model2.setFundCode("编码2");Model2.setFundName("名称2");// 该集合内容填充至模板二ArrayList<Model> list2 = Lists.newArrayList(Model1, Model2);ExcelWriter excelWriter = null;try {// 文件名称可自定义String fileName = String.format("自定义_%s_%s.xlsx", list1.get(0).getUsername(), LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));String encodeFileName = EncoderUtils.encodeToUtf8(fileName);HttpServletResponse response = WebUtils.getResponse();response.setCharacterEncoding(StandardCharsets.UTF_8.name());response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment;filename=" + encodeFileName);excelWriter = EasyExcel.write(response.getOutputStream()).build();// sheet名可自定义excelWriter.write(list1, EasyExcel.writerSheet(1, String.format("自定义_%s", "1")).head(TestDTO.class).build());// 动态指定单元格样式    String sheetName = "sheet2";// 行int rowIndex = 0;List<ExcelCellStyleModel> cellStyleList = new ArrayList<>();for (Model dto :list2) {if ("编码2".equals(dto.getFundCode())) {cellStyleList.add(ExcelCellStyleModel.createFontColorCellStyleModel(sheetName, rowIndex, 2, IndexedColors.RED));}rowIndex++;            }excelWriter.write(list2, EasyExcel.writerSheet(2, String.format("自定义_%s", "2")).registerWriteHandler(new ExcelCellStyleHandler(cellStyleList)).head(Model.class).build());} catch (IOException e) {log.error(e.getMessage(), e);throw new RuntimeException("导出自定义文件失败");} finally {if (excelWriter != null) {//关闭流excelWriter.finish();}}}

五、Excel 导入

  • 工具类
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.io.InputStream;
import java.util.List;/*** EasyExcel工具类** @author author* @date 2021/8/30 16:43*/
@Slf4j
public class EasyExcelUtils {/*** 解析MultipartFile文件中的sheet** @param file          excel文件* @param sheetName     需要解析的sheet名称* @param headRowNumber 表头行数,起始值为1* @param clazz         表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(MultipartFile file, String sheetName, int headRowNumber, Class<T> clazz) {InputStream inputStream = getInputStream(file);try {return parse(inputStream, sheetName, headRowNumber, clazz);} finally {IOUtils.closeQuietly(inputStream);}}private static InputStream getInputStream(MultipartFile file) {try {return file.getInputStream();} catch (IOException e) {log.error("MultipartFile转换为InputStream异常,文件名称:{}", file.getOriginalFilename());throw new RuntimeException("MultipartFile转换为InputStream异常");}}/*** 解析InputStream输入流中的sheet** @param inputStream   excel文件输入流* @param sheetName     需要解析的sheet名称* @param headRowNumber 表头行数,起始值为1* @param clazz         表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(InputStream inputStream, String sheetName, int headRowNumber, Class<T> clazz) {try {log.info("开始解析excel文件,sheet名称:{}", sheetName);List<T> list = EasyExcel.read(inputStream).sheet(sheetName).head(clazz).headRowNumber(headRowNumber).doReadSync();log.info("解析excel文件成功,sheet名称:{}", sheetName);return list;} catch (Exception e) {log.error("解析excel文件失败,sheet名称:{}", sheetName);throw new RuntimeException("解析excel文件失败");}}/*** 解析MultipartFile文件中的sheet,表头行数为1** @param file      excel文件* @param sheetName 需要解析的sheet名称* @param clazz     表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(MultipartFile file, String sheetName, Class<T> clazz) {return parse(file, sheetName, 1, clazz);}/*** 解析MultipartFile文件中的sheet** @param file          excel文件* @param sheetNumber   需要解析的sheet序号,起始值为1* @param headRowNumber 表头行数,起始值为1* @param clazz         表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(MultipartFile file, int sheetNumber, int headRowNumber, Class<T> clazz) {InputStream inputStream = getInputStream(file);try {return parse(inputStream, sheetNumber, headRowNumber, clazz);} finally {IOUtils.closeQuietly(inputStream);}}/*** 解析InputStream输入流中的sheet** @param inputStream   excel文件输入流* @param sheetNumber   需要解析的sheet序号,起始值为1* @param headRowNumber 表头行数,起始值为1* @param clazz         表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(InputStream inputStream, int sheetNumber, int headRowNumber, Class<T> clazz) {try {log.info("开始解析excel第{}个sheet文件", sheetNumber);List<T> list = EasyExcel.read(inputStream).sheet(sheetNumber - 1).head(clazz).headRowNumber(headRowNumber).doReadSync();log.info("解析excel第{}个sheet文件成功", sheetNumber);return list;} catch (Exception e) {log.error("解析excel第{}个sheet文件失败", sheetNumber);throw new RuntimeException("解析excel文件失败");}}/*** 解析MultipartFile文件中的第1个sheet** @param file          excel文件* @param headRowNumber 表头行数,起始值为1* @param clazz         表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(MultipartFile file, int headRowNumber, Class<T> clazz) {return parse(file, 1, headRowNumber, clazz);}/*** 解析MultipartFile文件中的第1个sheet,表头行数为1** @param file  excel文件* @param clazz 表格行对应的对象类型* @return java.util.List<T>*/public static <T> List<T> parse(MultipartFile file, Class<T> clazz) {return parse(file, 1, 1, clazz);}}
  • 使用实例 (涉及行数据对应对象定义参考多个sheet导出中model1定义及model2定义)
@ApiOperation(value = "解析excel文件", notes = "解析excel文件")@SysLog("解析excel文件")@PostMapping(value = "/parse", headers = "content-type=multipart/form-data")public void parse(@RequestPart("file") MultipartFile file) {// 解析文件中的sheet名称为模板二,表头为2行List<TestDTO> list1 = EasyExcelUtils.parse(file, "模板二", 2, TestDTO.class);// 解析文件中的sheet名称为模板一,表头默认为1行List<Model> list2 = EasyExcelUtils.parse(file, "模板一",Model.class);// 解析文件中的sheet序号为2,表头为2行List<TestDTO> list3 = EasyExcelUtils.parse(file, 2, 2, TestDTO.class);// 解析文件中的sheet默认序号为1,表头为1行List<Model> list4 = EasyExcelUtils.parse(file, 1, Model.class);// 解析文件中的sheet默认序号为1,默认表头为1行List<Model> list5 = EasyExcelUtils.parse(file, Model.class);}

转换器

  • 声明自定义转换器(以字符串转换为例)
public class CustomStringStringConverter implements Converter<String> {@Overridepublic Class supportJavaTypeKey() {return String.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}/*** 这里读的时候会调用,将表格数据cellData转换为字符串** @param cellData*            NotNull* @param contentProperty*            Nullable* @param globalConfiguration*            NotNull* @return*/@Overridepublic String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration) {return "自定义:" + cellData.getStringValue();}/*** 这里是写的时候会调用,将字符串value的值转换为表格数据** @param value*            NotNull* @param contentProperty*            Nullable* @param globalConfiguration*            NotNull* @return*/@Overridepublic CellData convertToExcelData(String value, ExcelContentProperty contentProperty,GlobalConfiguration globalConfiguration) {return new CellData(value);}}
  • 使用转化器
@Data
public class ConverterData {/*** 使用自定义 转换器,不管数据库传过来什么 。我给他加上“自定义:”*/@ExcelProperty(converter = CustomStringStringConverter.class)private String string;/*** 这里用string 去接日期才能格式化。我想接收年月日格式*/@DateTimeFormat("yyyy年MM月dd日HH时mm分ss秒")private String date;/*** 我想接收百分比的数字*/@NumberFormat("#.##%")private String doubleData;
}

其他用法

  • EasyExcel官方文档 https://easyexcel.opensource.alibaba.com/

Easy Excel 使用相关推荐

  1. Easy Excel生成压缩包文件,自定义表头样式

    Excel 文件内容形如下图! 需求场景 导出超10w左右的数据,涉及 源数据查. 组装业务数据 解析数据库中的json数据内容,并组装相应的信息 生成Excel文件内容到磁盘 将文件压缩,并写回到浏 ...

  2. 一小时教你轻松学会使用Java 整合 Easy Excel 操作 Excel 文件

    文章目录 一.Apache POI简介 二.POI操作Excel 构建maven项目导入依赖 使用POI实现基本写操作 使用POI实现大数据量写操作 使用POI实现基本读操作 使用POI读取不同类型的 ...

  3. 【RuoYi-Vue-Plus】学习笔记 42 - Easy Excel(二)Excel 2007(*.xlsx)导入流程分析(源码)

    文章目录 前言 参考目录 框架集成 1.Maven 2.框架集成公共部分 2.1.Excel 操作工具类 `ExcelUtil` 2.2.导入监听接口 `ExcelListener` 2.3.默认监听 ...

  4. Easy Excel

    Easy Excel Easy Excel 1. 为什么有使用easyexcle 2. easvexcel拟解决的问题 3. 工作原理 4. ORM根据数据库表创建实体类的一个小技巧 5. 写exce ...

  5. Easy Excel 使用总结

    title: Easy Excel 使用总结 date: 2022-10-14 17:33:57 tags: Excel categories: 开发技术及框架 cover: https://cove ...

  6. Easy Excel使用说明

    Easy Excel使用说明 官网使用说明 这里啥都有,好好利用,好好看. 1.maven引入包 <!-- https://mvnrepository.com/artifact/com.alib ...

  7. Easy Excel读取复杂表格文件

    表格内容如下 分析 该文档总共9个Sheet页 以Sheet0(客户交易结算月报)为例:表格总共分为4个部分(图中红色部分).一.二部分数据为横向数据(字段名:字段值),三四部分为纵向集合.第四部分每 ...

  8. 【RuoYi-Vue-Plus】学习笔记 41 - Easy Excel(一)Excel 2003(*.xls)导入流程分析(源码)

    文章目录 前言 参考目录 框架集成 1.Maven 2.框架集成公共部分 2.1.Excel 操作工具类 `ExcelUtil` 2.2.导入监听接口 `ExcelListener` 2.3.默认监听 ...

  9. 使用Easy Excel对excel的读写

    目录 Easy Excel 所需依赖 准备一个excel文件 对excel的读取 创建对应的实体类 创建EasyExcelUtil类 修改实体类 对excel的写入 在EasyExcelUtil类中加 ...

  10. Easy Excel 解析Excel

    起因:工作中有同事使用Easy Excel解析上传的Excel文件,记录一下使用方式,其实官方文档写的够详细了,官方文档: https://easyexcel.opensource.alibaba.c ...

最新文章

  1. php定时爬虫,thinkphp5使用workerman定时器定时爬取站点内容的代码
  2. java 什么时候依赖注入_玩框架java依赖注入 – 何时使用单例
  3. Android安全与逆向之Java虚拟机和Dalvik虚拟机的区别
  4. html type=text/css,type=text/css 有什么用啊 ?
  5. Python基础知识(3)
  6. 两本好书可能改变的我一生——致出版社的一封信!
  7. spring源码解析bean定义五ContextNamespaceHandler一
  8. 莫队--2038: [2009国家集训队]小Z的袜子(hose)
  9. 360安全卫士对于易量安装打包的可执行程序进行病毒误报
  10. 系统测试计划编写(四)
  11. cad项目数据库服务器,cad项目数据库服务器
  12. 求三点共圆求圆心半径及其推导(三角形外心)
  13. Linux磁盘16进制编辑,Tweak
  14. Python实现基于负熵最大判据的FastICA胎心信号分离
  15. 苹果6性能测试软件,5款iPhone升级iOS13.6性能测试:运行速度有所提升?
  16. 天平游码读数例题_“天平”典型题析
  17. 尘埃落定!AI 大牛贾佳亚离开腾讯优图,创立思谋科技,投身差异化 AI 创业
  18. 【成电860考研】经验贴汇总(公共课+专业课+复试)-扒遍所有网站:信软群、王道、知乎、csdn等,截止21年7月整理出的所有帖子-共15篇
  19. SQL取整与时间差值返回
  20. 在win10中AsciiDoc使用plantUML的使用报错:Dot Executable:C:\Program Files\Graphviz2.38 it should be an executa

热门文章

  1. 自己开发的安卓,电脑远控
  2. 2022年最新贴吧gif防删图制作过程解析?当你学会防图,你就能随心所欲的控图
  3. Android ImageButton(图片按钮)
  4. 【案例】“1GB1年1毛钱“——使用 Backup exec 基于阿里云OSS 实现企业数据异地备份 【服务器管理】【云备份】
  5. Element ui后台管理系统界面设计
  6. Altium Designer 封装绘制时批量重命名焊盘编号
  7. 2022考研真题+汤家凤网课视频。祝2022考研朋友顺利上岸!
  8. Xv6操作系统导论(第三章)
  9. 网络安全之几种常见的黑客攻击手段
  10. 网络入侵检测--Snort软件NIDS模式报警信息详解