SpringBoot+EasyExcel實現(xiàn)自定義復(fù)雜樣式導(dǎo)入導(dǎo)出
tips:能用模板就用模板,當(dāng)模板不適用的情況下,再選擇自定義生成 Excel。
官網(wǎng):https://easyexcel.opensource.alibaba.com
安裝
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.1</version>
</dependency>
處理自定義導(dǎo)出復(fù)雜場景
1、列不固定,動態(tài)列
2、動態(tài)下拉
3、自定義鎖定行/列,添加密碼
4、合并單元格
5、導(dǎo)入自定義統(tǒng)一注解統(tǒng)一校驗
6、樣式處理(字體,顏色,底色,富文本,列寬,行寬等)
7、凍結(jié)窗格
8、多Sheet處理
1、列不固定,動態(tài)列
首先定義一個公共實體,處理公共字段和動態(tài)列字段,具體實體則繼承該類即可。
package com.example.springbootexcel.excel.base.model;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class BaseExcel {
@ExcelProperty( value = "序號")
private String num;
/**
* 動態(tài)字段處理
*/
private List<Map<String, Object>> dynamicList;
}
2、動態(tài)下拉
封裝一個公共類,構(gòu)造入?yún)ap,key為表頭,value為下拉字符串?dāng)?shù)組。
.registerWriteHandler(new DropDownHandler(dropDownMap));
package com.example.springbootexcel.excel.base.style;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;
import java.util.Map;
/**
* 添加下拉選單
*
* @author jason
*/
public class DropDownHandler implements SheetWriteHandler {
private final Map<Integer, String[]> dropDownMap; // key:列號(從0開始), value:下拉數(shù)據(jù)
public DropDownHandler(Map<Integer, String[]> dropDownMap) {
this.dropDownMap = dropDownMap;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
// 不需要實現(xiàn)
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
if (dropDownMap == null || dropDownMap.isEmpty()) {
return;
}
Sheet sheet = writeSheetHolder.getSheet();
DataValidationHelper helper = sheet.getDataValidationHelper();
dropDownMap.forEach((columnIndex, dropDownData) -> {
// 設(shè)置下拉框數(shù)據(jù)范圍 (這里設(shè)置從第2行到第10000行)
CellRangeAddressList addressList = new CellRangeAddressList(1, 9999, columnIndex, columnIndex);
// 創(chuàng)建數(shù)據(jù)驗證約束
DataValidationConstraint constraint = helper.createExplicitListConstraint(dropDownData);
// 創(chuàng)建數(shù)據(jù)驗證
DataValidation validation = helper.createValidation(constraint, addressList);
// 阻止輸入非下拉選項的值
validation.setErrorStyle(DataValidation.ErrorStyle.STOP);
validation.setShowErrorBox(true);
validation.setSuppressDropDownArrow(true);
validation.createErrorBox("提示", "請從下拉選項中選擇");
// 添加驗證到sheet
sheet.addValidationData(validation);
});
}
}
3、自定義鎖定行/列,添加密碼
@Override
public void afterCellCreate(CellWriteHandlerContext context) {
WriteSheetHolder writeSheetHolder = context.getWriteSheetHolder();
Sheet sheet = writeSheetHolder.getSheet();
Workbook workbook = sheet.getWorkbook();
Cell cell = context.getCell();
int columnIndex = cell.getColumnIndex();
Row row = cell.getRow();
// 設(shè)置工作表保護
if (!sheet.getProtect()) {
XSSFSheet xssfSheet = (XSSFSheet) sheet;
// 啟用保護
xssfSheet.protectSheet("1234");
// 設(shè)置保護選項:允許刪除未鎖定行
xssfSheet.lockDeleteRows(false);
// 設(shè)置保護選項:允許插入未鎖定行
xssfSheet.lockInsertRows(false);
}
// 設(shè)置工作表的默認單元格樣式為不鎖定
CellStyle defaultStyle = workbook.createCellStyle();
defaultStyle.setLocked(false);
sheet.setDefaultColumnStyle(columnIndex, defaultStyle);
row.setRowStyle(defaultStyle);
}
4、合并單元格
sheet.addMergedRegion(new CellRangeAddress(relativeRowIndex, relativeRowIndex, 0, 10));
5、導(dǎo)入自定義統(tǒng)一注解統(tǒng)一校驗
package com.example.springbootexcel.excel.base.component;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* tips:非必填校驗,填了就校驗,不填不校驗
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface ExcelValidation {
/**
* 日期校驗
*
* @return true表示必須為日期,false表示不限制
*/
boolean date() default false;
/**
* 是否必須為數(shù)字
*
* @return true表示必須為數(shù)字,false表示不限制
*/
boolean numeric() default false;
/**
* 是否允許小數(shù),且最多兩位小數(shù)
*
* @return true表示允許最多兩位小數(shù),false表示不允許小數(shù)
*/
boolean decimal() default false;
/**
* 是否允許斜杠
*
* @return true表示允許斜杠,false表示不允許
*/
boolean allowSlash() default false;
/**
* 校驗失敗時的錯誤提示信息
*
* @return 錯誤提示信息
*/
String message() default "字段校驗失敗";
}
6、樣式處理(字體,顏色,底色,富文本,列寬,行寬等)
// 基本樣式設(shè)置
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
// 設(shè)置水平對齊為左對齊
cellStyle.setAlignment(HorizontalAlignment.LEFT);
// 設(shè)置垂直對齊為垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 設(shè)置自動換行
cellStyle.setWrapText(true);
// 創(chuàng)建默認字體
Font defaultFont = workbook.createFont();
defaultFont.setFontName(DEFAULT_FONT_NAME);
defaultFont.setFontHeightInPoints(DEFAULT_FONT_POINTS);
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
// 創(chuàng)建紅色字體
Font redFont = workbook.createFont();
redFont.setFontName(DEFAULT_FONT_NAME);
redFont.setFontHeightInPoints(DEFAULT_FONT_POINTS);
redFont.setColor(IndexedColors.RED.getIndex());
redFont.setBold(true);
// 自定義列寬
String cellValue = cell.getStringCellValue();
Integer columnWidth = COLUMN_WIDTHS.get(cellValue);
if (ObjectUtil.isNotNull(columnWidth) && !CollectionUtil.contains(COLUMN_WIDTHS_EXIST, context.getColumnIndex())) {
sheet.setColumnWidth(context.getColumnIndex(), columnWidth);
COLUMN_WIDTHS_EXIST.add(context.getColumnIndex());
}
// 設(shè)置默認寬度
if (!CollectionUtil.contains(COLUMN_WIDTHS_EXIST, context.getColumnIndex())) {
sheet.setColumnWidth(context.getColumnIndex(), DEFAULT_COLUMN_WIDTH);
}
// 提示詞
if (CollectionUtil.contains(TIPS_LIST, relativeRowIndex)) {
defaultFont = redFont;
// 合并單元格
sheet.addMergedRegion(new CellRangeAddress(relativeRowIndex, relativeRowIndex, 0, 10));
}
// 表頭
if (CollectionUtil.contains(HEAD_LIST, relativeRowIndex)) {
defaultFont.setBold(true);
// 背景色
cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
// 動態(tài)字段標(biāo)紅
if (CollectionUtil.contains(HEAD_READ_COLOR, cell.getColumnIndex())) {
defaultFont = redFont;
} else {
// 星號標(biāo)紅
RichTextString richText = cell.getRichStringCellValue();
if (StrUtil.startWith(cellValue, "*")) {
richText.applyFont(0, 1, redFont);
if (cellValue.length() > 1) {
richText.applyFont(1, cellValue.length(), defaultFont);
}
cell.setCellValue(richText);
}
}
}
cellStyle.setFont(defaultFont);
7、凍結(jié)窗格
.registerWriteHandler(new FreezePaneHandler(2))
package com.example.springbootexcel.excel.base.style;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;
/**
* 凍結(jié)窗格
*
* @author jason
*/
public class FreezePaneHandler implements SheetWriteHandler {
private final int row; // 需要凍結(jié)的行
public FreezePaneHandler(int row) {
this.row = row;
}
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
Sheet sheet = writeSheetHolder.getSheet();
// 凍結(jié)首行
// sheet.createFreezePane(0, 1, 0, 1);
sheet.createFreezePane(0, row, 0, row);
}
}
8、多Sheet處理
// 創(chuàng)建 ExcelWriter 對象
ExcelWriter excelWriter = EasyExcel.write(filePath).inMemory(true).build();
// 寫入第1個 Sheet
WriteSheet sheet1 = EasyExcel.writerSheet("Sheet1")
.registerWriteHandler(new CommonStyleHandler(MockDataUtil.getHeadReadColor(headList, dynamicList)))
.registerWriteHandler(new DropDownHandler(dropDownMap))
.registerWriteHandler(new FreezePaneHandler(2))
.build();
excelWriter.write(sheet1DataList, sheet1);
// 寫入第2個 Sheet
WriteSheet sheet2 = EasyExcel.writerSheet("Sheet2")
.head(BrandModelExcel.class)
.registerWriteHandler(new FreezePaneHandler(1))
.build();
excelWriter.write(MockDataUtil.brandModelExcelList(), sheet2);
// 寫入第3個 Sheet
WriteSheet sheet3 = EasyExcel.writerSheet("Sheet3")
.head(VehicleNameExcel.class)
.registerWriteHandler(new FreezePaneHandler(1))
.build();
excelWriter.write(MockDataUtil.vehicleNameExcelList(), sheet3);
// 非常重要:最后一定要關(guān)閉 excelWriter
excelWriter.finish();
log.info("導(dǎo)出成功:{}", filePath);
源碼:https://gitee.com/zhaomingjian/workspace_dora/tree/master/spring-boot-excel
到此這篇關(guān)于SpringBoot+EasyExcel實現(xiàn)自定義復(fù)雜樣式導(dǎo)入導(dǎo)出的文章就介紹到這了,更多相關(guān)SpringBoot EasyExcel自定義樣式導(dǎo)入導(dǎo)出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot?整合?EasyExcel?實現(xiàn)自由導(dǎo)入導(dǎo)出功能
- SpringBoot整合EasyExcel實現(xiàn)批量導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實現(xiàn)復(fù)雜Excel表格的導(dǎo)入導(dǎo)出
- 使用SpringBoot與EasyExcel實現(xiàn)復(fù)雜的導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實現(xiàn)導(dǎo)入導(dǎo)出功能
- SpringBoot中EasyExcel實現(xiàn)execl導(dǎo)入導(dǎo)出
- SpringBoot整合EasyExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)
- SpringBoot整合EasyExcel實現(xiàn)文件導(dǎo)入導(dǎo)出
- SpringBoot中EasyExcel實現(xiàn)Excel文件的導(dǎo)入導(dǎo)出
相關(guān)文章
@SpringBootConfiguration重復(fù)加載報錯問題解決
@SpringBootApplication?注解的?exclude?屬性用于排除特定的自動配置類,而不是用于排除主配置類本身,因此,不能通過?exclude?屬性來排除主配置類的加載,這篇文章主要介紹了@SpringBootConfiguration重復(fù)加載報錯,需要的朋友可以參考下2024-08-08
關(guān)于java中@Async異步調(diào)用詳細解析附代碼
本文主要介紹了java關(guān)于@Async異步調(diào)用詳細解析附代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Java動態(tài)追蹤技術(shù)探究之從JSP到Arthas
這篇文章主要介紹了Java動態(tài)追蹤技術(shù)探究之從JSP到Arthas,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,,需要的朋友可以參考下2019-06-06

