文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java 导出Excel表格生成下拉框-EasyExcel

2023-09-22 12:09

关注

1.导入EasyExcel,maven依赖

                    com.alibaba            easyexcel            2.2.10        

2.添加EasyExcelUtil工具类

package org.springblade.modules.system.EuipmentExcelImplement;import com.alibaba.excel.EasyExcel;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.write.metadata.WriteSheet;import lombok.extern.slf4j.Slf4j;import java.lang.reflect.Field;import java.util.HashMap;import java.util.Map;@Slf4jpublic class EasyExcelUtil {public static  WriteSheet writeSelectedSheet(Class head, Integer sheetNo, String sheetName) {Map selectedMap = resolveSelectedAnnotation(head);return EasyExcel.writerSheet(sheetNo, sheetName).head(head).registerWriteHandler(new SelectedSheetWriteHandler(selectedMap)).build();}private static  Map resolveSelectedAnnotation(Class head) {Map selectedMap = new HashMap<>();// getDeclaredFields(): 返回全部声明的属性;getFields(): 返回public类型的属性Field[] fields = head.getDeclaredFields();for (int i = 0; i < fields.length; i++){Field field = fields[i];// 解析注解信息ExcelSelected selected = field.getAnnotation(ExcelSelected.class);ExcelProperty property = field.getAnnotation(ExcelProperty.class);if (selected != null) {ExcelSelectedResolve excelSelectedResolve = new ExcelSelectedResolve();String[] source = excelSelectedResolve.resolveSelectedSource(selected);if (source != null && source.length > 0){excelSelectedResolve.setSource(source);excelSelectedResolve.setFirstRow(selected.firstRow());excelSelectedResolve.setLastRow(selected.lastRow());if (property != null && property.index() >= 0){selectedMap.put(property.index(), excelSelectedResolve);} else {selectedMap.put(i, excelSelectedResolve);}}}}return selectedMap;}}
package org.springblade.modules.system.EuipmentExcelImplement;import com.alibaba.excel.write.handler.SheetWriteHandler;import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;import lombok.AllArgsConstructor;import lombok.Data;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;@Data@AllArgsConstructorpublic class SelectedSheetWriteHandler implements SheetWriteHandler {private final Map selectedMap;@Overridepublic void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}@Overridepublic void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {// 这里可以对cell进行任何操作Sheet sheet = writeSheetHolder.getSheet();DataValidationHelper helper = sheet.getDataValidationHelper();selectedMap.forEach((k, v) -> {// 设置下拉列表的行: 首行,末行,首列,末列CellRangeAddressList rangeList = new CellRangeAddressList(v.getFirstRow(), v.getLastRow(), k, k);// 设置下拉列表的值DataValidationConstraint constraint = helper.createExplicitListConstraint(v.getSource());// 设置约束DataValidation validation = helper.createValidation(constraint, rangeList);// 阻止输入非下拉选项的值validation.setErrorStyle(DataValidation.ErrorStyle.STOP);validation.setShowErrorBox(true);validation.setSuppressDropDownArrow(true);validation.createErrorBox("提示", "请输入下拉选项中的内容");sheet.addValidationData(validation);});}}

3 .创建实体类

package org.springblade.modules.question.entity;import com.alibaba.excel.annotation.ExcelIgnore;import com.alibaba.excel.annotation.ExcelProperty;import com.alibaba.excel.annotation.write.style.ColumnWidth;import com.alibaba.excel.annotation.write.style.ContentRowHeight;import com.alibaba.excel.annotation.write.style.HeadRowHeight;import io.swagger.annotations.ApiModelProperty;import lombok.Data;import org.springblade.modules.question.excelImplement.*;import org.springblade.modules.system.EuipmentExcelImplement.DeptSelectedImpl;import org.springblade.modules.system.EuipmentExcelImplement.ExcelSelected;import java.io.Serializable;@Data@ColumnWidth(16)@HeadRowHeight(20)@ContentRowHeight(18)public class QuestionExcel implements Serializable {private static final long serialVersionUID = 1L;@ExcelIgnore //忽略生成表头//@ExcelSelected(sourceClass = CourseSelected.class)private String courseName;@ExcelProperty(index = 0,value ="课程章节名称")//表头名称@ExcelSelected(sourceClass = ChapterSelected.class)private String chapterName;@ExcelProperty(index = 1,value ="实验名称")@ColumnWidth(25)@ExcelSelected(sourceClass = ExperimentSelected.class)private String experimentName;@ExcelProperty(index = 2,value ="题型(1:单选2:多选3:判断4:问答)")@ExcelSelected(sourceClass = TypeSelected.class)private String questionType;}

4.导入自定义注解ExcelSelected

package org.springblade.modules.system.EuipmentExcelImplement;import java.lang.annotation.*;@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD)public @interface ExcelSelected {String[] source() default {};Class[] sourceClass() default {};int firstRow() default 1;int lastRow() default 0x10000;}

5.导入Excel选择解析-ExcelSelectedResolve 

package org.springblade.modules.system.EuipmentExcelImplement;import lombok.Data;import lombok.extern.slf4j.Slf4j;@Data@Slf4jpublic class ExcelSelectedResolve {private String[] source;private int firstRow;private int lastRow;public String[] resolveSelectedSource(ExcelSelected excelSelected) {if (excelSelected == null) {return null;}// 获取固定下拉框的内容String[] source = excelSelected.source();if (source.length > 0) {return source;}// 获取动态下拉框的内容Class[] classes = excelSelected.sourceClass();if (classes.length > 0) {try {ExcelDynamicSelect excelDynamicSelect = classes[0].newInstance();String[] dynamicSelectSource = excelDynamicSelect.getSource();if (dynamicSelectSource != null && dynamicSelectSource.length > 0) {return dynamicSelectSource;}} catch (InstantiationException | IllegalAccessException e) {log.error("解析动态下拉框数据异常", e);}}return null;}}

6.添加动态选择接口-ExcelDynamicSelect

package org.springblade.modules.system.EuipmentExcelImplement;public interface ExcelDynamicSelect {String[] getSource();}

7.编写自己需要展示下拉框实现-ExcelDynamicSelect接口

package org.springblade.modules.question.excelImplement;import org.apache.commons.collections.CollectionUtils;import org.springblade.core.log.exception.ServiceException;import org.springblade.modules.question.mapper.QuestionMapper;import org.springblade.modules.system.EuipmentExcelImplement.ExcelDynamicSelect;import org.springblade.modules.system.EuipmentExcelImplement.SpringContextUtil;import java.util.List;public class ChapterSelected implements ExcelDynamicSelect {@Overridepublic String[] getSource() {QuestionMapper questionMapper = SpringContextUtil.getBean(QuestionMapper.class);return questionMapper.selectAllChapter().toArray(new String[]{});}}

8.添加SpringContextUtil工具类

package org.springblade.modules.system.EuipmentExcelImplement;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class SpringContextUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextUtil.applicationContext = applicationContext;}// 获取ApplicationContextpublic static ApplicationContext getApplicationContext() {return applicationContext;}// 通过class获取Beanpublic static  T getBean(Class clazz) {return applicationContext.getBean(clazz);}// 通过name以及class获取Beanpublic static  T getBean(String name, Class clazz) {return applicationContext.getBean(name, clazz);}}

9.编写查询下拉框显示内容mapping

public interface QuestionMapper extends BaseMapper {public List selectAllChapter();}
  

10.也可以不查询数据库,直接再接口返回需要的数据。

package org.springblade.modules.question.excelImplement;import org.springblade.modules.question.mapper.QuestionMapper;import org.springblade.modules.system.EuipmentExcelImplement.ExcelDynamicSelect;import org.springblade.modules.system.EuipmentExcelImplement.SpringContextUtil;import java.util.ArrayList;public class TypeSelected implements ExcelDynamicSelect {@Overridepublic String[] getSource() {//直接返回需要的数据return new ArrayList(){{add("单选");add("多选");add("判断");add("问答");}}.toArray(new String[]{});}}

11.最终效果

 

来源地址:https://blog.csdn.net/weixin_53335648/article/details/130484195

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯