Easy Excel 使用

一、引入依赖

<!-- 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());
	}
	
	@Override
	public 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();
		// 克隆出一个 style
		style.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
	@ExcelIgnore
	private String id;
	
	/**
	 * 批量导入日期
	 */
	@ExcelIgnore
	private 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导出

// 指定单元格样式
List<ExcelCellStyleModel> cellStyleList = new ArrayList<>();
for (int i = 0; i < userList.size(); i++) {
	cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 7, "#,##0.0000"));
	cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 8, "#,##0.00"));
	cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 9, "#,##0.0000"));
}
try {
	String encodeFileName = EncoderUtils.encodeToUtf8(fileName + excelTypeEnum.getValue());
	HttpServletResponse response = WebUtils.getResponse();
	response.setHeader("Content-disposition", "attachment;filename=" + encodeFileName);
	response.setContentType("application/vnd.ms-excel");
	response.setCharacterEncoding(StandardCharsets.UTF_8.name());
	// response获取的流是ServletOutputStream,请求执行完会自动销毁,无需手动关闭
	// 且如果手动了,将会直接返回response信息,虽然后面的代码会继续执行处理,但已经不会影响给前端的返回值了
	OutputStream outputStream = response.getOutputStream();
	
	// 单个sheet
	// EasyExcel.write(outputStream, User.class)
	// 		.sheet(0, sheetName)
	// 		.registerWriteHandler(new ExcelCellStyleHandler(cellStyleList))
	// 		.doWrite(userList);
	
	// 多个sheet
	ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
	for (Map.Entry<String, List<User>> entry : userMap.entrySet()) {
		String sheetName = entry.getKey();
		WriteSheet writeSheet = EasyExcel.writerSheet(Integer.valueOf(entry.getKey()), sheetName)
				.registerWriteHandler(new ExcelCellStyleHandler(cellStyleList))
				.head(User.class)
				.build();
		excelWriter.write(entry.getValue(), writeSheet);
	}
	// 多个sheet也不能带finally里执行finish,否则返回信息中会拼接之前暂存的流内容,及时catch里执行了reset
	excelWriter.finish();
	
} catch (Exception e) {
	// 因为前面处理的response,这里需要重置,否则catch中继续抛出异常,返回值也不是全局拦截处理后的数据信息
	WebUtils.getResponse().reset();
	
	throw new RuntimeException("导出失败", e);
}

七、Excel生成

HashMap<String, byte[]> fileMap = new HashMap<>(1);

   try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
      String sheetName = String.format("%s文件", stockCode);
      String fileName = String.format("%s.xlsx", sheetName);
      // 指定单元格样式
      List<ExcelCellStyleModel> cellStyleList = new ArrayList<>();
      for (int i = 0; i < userList.size(); i++) {
         cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 4, "#,##0.00"));
         cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 5, "#,##0"));
         cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 6, "#,##0.00"));
         cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 8, "#,##0.00"));
         cellStyleList.add(ExcelCellStyleModel.createDataFormatCellStyleModel(sheetName, i, 9, "#,##0.00"));
      }
      // 将文件写入到声明的字节流中
      EasyExcel.write(bos, User.class)
            .sheet(0, sheetName)
            .registerWriteHandler(new ExcelCellStyleHandler(cellStyleList))
            .doWrite(userList);
            
      fileMap.put(fileName, bos.toByteArray());
   } catch (Exception e) {
      throw new RuntimeException("生成文件失败", e);
   }

八、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> {
    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里读的时候会调用,将表格数据cellData转换为字符串
     *
     * @param cellData
     *            NotNull
     * @param contentProperty
     *            Nullable
     * @param globalConfiguration
     *            NotNull
     * @return
     */
    @Override
    public String convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
        GlobalConfiguration globalConfiguration) {
        return "自定义:" + cellData.getStringValue();
    }

    /**
     * 这里是写的时候会调用,将字符串value的值转换为表格数据
     *
     * @param value
     *            NotNull
     * @param contentProperty
     *            Nullable
     * @param globalConfiguration
     *            NotNull
     * @return
     */
    @Override
    public 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/
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用easy excel导出Excel文件可以通过以下步骤完成: 1. 首先,确保已经安装了Java开发环境以及easyexcel的相关依赖包,例如alibaba easyexcel。 2. 导入easyexcel相关的类和包,例如`com.alibaba.excel.EasyExcel`。 3. 创建一个ExcelWriter对象,用于写入Excel文件。可以指定要生成的Excel文件的路径和文件名。 4. 创建一个Sheet对象,并设置sheet的名称。 5. 创建一个List集合,用于存储要导出的数据。 6. 将数据逐一添加到List集合中。 7. 调用ExcelWriter对象的write方法,将数据写入到Sheet中。 8. 最后,调用ExcelWriter对象的finish方法,关闭资源,生成Excel文件。 下面是一个示例代码: ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Table; import java.util.ArrayList; import java.util.List; public class ExportExcel { public static void main(String[] args) { // 创建ExcelWriter对象,并指定要生成的Excel文件的路径及名称 ExcelWriter excelWriter = EasyExcel.write("D:\\test.xlsx").build(); // 创建Sheet对象,并设置sheet的名称 Sheet sheet = new Sheet(1, 0); sheet.setSheetName("Sheet1"); // 创建一个 List 集合,用于存储要导出的数据 List<List<String>> data = new ArrayList<>(); // 向 List 中逐一添加数据 List<String> item = new ArrayList<>(); item.add("姓名"); item.add("年龄"); data.add(item); item = new ArrayList<>(); item.add("张三"); item.add("25"); data.add(item); // 将数据写入到 Sheet 中 excelWriter.write(data, sheet); // 关闭资源,生成Excel文件 excelWriter.finish(); } } ``` 以上代码会生成一个名为test.xlsx的Excel文件,其中包含一个名为Sheet1的工作表,表格中有两列数据:姓名和年龄,其中姓名为张三,年龄为25。 这样就可以使用easyexcel导出Excel文件了。注意,使用easyexcel还可以导出更复杂的Excel文件,例如多个工作表、自定义样式等。详细的用法可以参考easyexcel的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值