spring boot 根据easyexcel导出excel 设置下拉框(字典值)
在Spring Boot中使用EasyExcel导出Excel并设置下拉框(字典值),你可以通过自定义ExcelWriteHandler
来实现。以下是一个简化的例子:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.handler.AbstractColumnWidthStyleStrategy;
import com.alibaba.excel.write.handler.ExcelWriteHandler;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import java.util.List;
public class DictionaryDropdownHandler implements ExcelWriteHandler {
private int sheetNum; // 当前sheet的序号
private int startRow; // 开始行
private int endRow; // 结束行
private int colIndex; // 需要设置下拉的列索引
private List<String> dictionary; // 字典列表
public DictionaryDropdownHandler(int sheetNum, int startRow, int endRow, int colIndex, List<String> dictionary) {
this.sheetNum = sheetNum;
this.startRow = startRow;
this.endRow = endRow;
this.colIndex = colIndex;
this.dictionary = dictionary;
}
@Override
public void beforeSheetCreate(WriteSheet writeSheet) {
// 在这里不需要做任何操作
}
@Override
public void afterSheetCreate(WriteSheet writeSheet, Sheet sheet) {
if (sheet.getWorkbook().getSheetIndex(sheet) == sheetNum) {
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createExplicitListConstraint(dictionary.toArray(new String[0]));
CellRangeAddressList addressList = new CellRangeAddressList(startRow, endRow, colIndex, colIndex);
DataValidation dataValidation = helper.createValidation(constraint, addressList);
sheet.addValidationData(dataValidation);
}
}
}
// 使用示例
List<List<String>> data = ...; // 数据
List<String> dictionary = Arrays.asList("字典1", "字典2", "字典3"); // 字典值
String fileName = "example.xlsx";
EasyExcel.write(fileName, List.class)
.registerWriteHandler(new DictionaryDropdownHandler(0, 1, 100, 0, dictionary)) // 假设是第一个sheet,数据从第二行开始,设置第一列的下拉列表
.sheet("Sheet1")
.doWrit
评论已关闭