当前位置: 首页 > news >正文

使用easypoi读取Excel模板

  • 1、只读取一个脚本号=====Excel
  • 2、读取多个脚本号的sheet…=====Excel

1、只读取sheet0(只读取一个脚本号的Excel)

  • 前言:引入pom文件
  <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel-core</artifactId><version>3.3.2</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.2</version></dependency>
  • 读取文件模板
    在这里插入图片描述

  • 读取文件实体

//注意Excel 引入的包
//注意Excel 引入的包
//注意Excel 引入的包
import cn.afterturn.easypoi.excel.annotation.Excel;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestDto {@Excel(name = "姓名")private String name;@Excel(name = "年龄")private int age;@Excel(name = "性别")private String sex;
}
  • 读取文件
//controller层
public class ExcelImportController {@Autowiredprivate ExcelImportServiceImpl excelImportService;@PostMapping("/import")@ApiOperation(value = "批量导入")public void importExcel() {File file = new File("D:\\maven_workplace\\Aproject-GJ\\yh-calculation-server\\calculation\\src\\main\\resources\\test.xlsx");return excelImportService.importExcel(file);}
}
//service层
@Service
public class ExcelImportServiceImpl {@Autowiredprivate LossComputeService lossComputeService;public void importExcel(File file) {//文件进行校验
//        checkFile(file);//获取excel文件List<TestDto> excelImportCos = EasyExcelUtil.importExcel(file, TestDto.class);System.out.println("输出excel返回实体======>"+excelImportCos.toString());ArrayList<TestDto> testDtos = new ArrayList<>();for (TestDto testDto : excelImportCos) {TestDto dto = new TestDto();dto.setName(testDto.getName());dto.setAge(testDto.getAge());dto.setSex(testDto.getSex());testDtos.add(testDto);}System.out.println("输出封装到实体中的数据======>"+ testDtos.toString());return null;}
//EasyExcelUtil  工具类@Component
@Slf4j
public class EasyExcelUtil {public static <T> List<T> importExcel(File file, Class<T> pojoClass)  {ImportParams params = new ImportParams();params.setTitleRows(0);params.setHeadRows(1);params.setKeyIndex(1);return  importExcelExcep(file, pojoClass, params);}private static <T> List<T> importExcelExcep(File file, Class<T> pojoClass, ImportParams params) {List<T> list = null;try {//ExcelImportUtil  是包   cn.afterturn.easypoi.excel;list = ExcelImportUtil.importExcel(file, pojoClass, params);
//            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);} catch (Exception e) {log.error("导入失败",e);throw new RuntimeException("导入失败");}return list;}
}

结果:
在这里插入图片描述


2、读取多个脚本号的sheet…的Excel

  • 前言:引入pom文件
  <dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel-core</artifactId><version>3.3.2</version></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.1.2</version></dependency>
  • 读取文件模板
    在这里插入图片描述
    在这里插入图片描述

  • 读取文件实体

//注意Excel 引入的包
//注意Excel 引入的包
//注意Excel 引入的包
import cn.afterturn.easypoi.excel.annotation.Excel;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestDto {@Excel(name = "姓名")private String name;@Excel(name = "年龄")private int age;@Excel(name = "性别")private String sex;
}
------------------------------------------------另一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test2Dto {@Excel(name = "姓名")private String name;@Excel(name = "年龄")private int age;@Excel(name = "时间")private String time;
}
  • 读取文件
//controller层
public class ExcelImportController {@Autowiredprivate ExcelImportServiceImpl excelImportService;@PostMapping("/import")@ApiOperation(value = "批量导入")public AjaxResult<LossCalculationLog> importExcel() {File file = new File("D:\\maven_workplace\\Aproject-GJ\\yh-calculation-server\\calculation\\src\\main\\resources\\test.xlsx");return excelImportService.importExcel(file);}}//service层
@Service
public class ExcelImportServiceImpl {@Autowiredprivate LossComputeService lossComputeService;public AjaxResult<LossCalculationLog> importExcel(File file) {//文件进行校验
//        checkFile(file);//获取所有字段名称String[] allIsExcelFields = EasyExcelUtil.getAllIsExcelFields(TestDto.class);System.out.println("获取的所有的字段名称"+allIsExcelFields.toString());//获取list字段sheet0List<TestDto> excelImportCos = EasyExcelUtil.importExcelBatch(file, 0, TestDto.class, allIsExcelFields);System.out.println("输出excel返回实体======>"+excelImportCos.toString());ArrayList<TestDto> testDtos = new ArrayList<>();for (TestDto testDto : excelImportCos) {TestDto dto = new TestDto();dto.setName(testDto.getName());dto.setAge(testDto.getAge());dto.setSex(testDto.getSex());testDtos.add(testDto);}System.out.println("输出sheet0 封装到实体中的数据======>"+ testDtos.toString());String[] allIsExcelFields1 = EasyExcelUtil.getAllIsExcelFields(Test2Dto.class);//获取list字段sheet0,List<Test2Dto> excelImportCos1 = EasyExcelUtil.importExcelBatch(file, 1, Test2Dto.class, allIsExcelFields1);System.out.println("输出excel返回实体======>"+excelImportCos1.toString());ArrayList<Test2Dto> testDtos1 = new ArrayList<>();for (Test2Dto testDto : excelImportCos1) {Test2Dto dto = new Test2Dto();dto.setName(testDto.getName());dto.setAge(testDto.getAge());dto.setTime(testDto.getTime());testDtos1.add(dto);}System.out.println("输出sheet1 封装到实体中的数据======>"+ testDtos1.toString());//封装请求体,并调用损失计算服务
return null;}
}// EasyExcelUtil 工具@Component
@Slf4j
public class EasyExcelUtil {public static <T> List<T> importExcel(File file, Class<T> pojoClass)  {ImportParams params = new ImportParams();params.setTitleRows(0);params.setHeadRows(1);params.setKeyIndex(1);return  importExcelExcep(file, pojoClass, params);}private static <T> List<T> importExcelExcep(File file, Class<T> pojoClass, ImportParams params) {List<T> list = null;try {list = ExcelImportUtil.importExcel(file, pojoClass, params);
//            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);} catch (Exception e) {log.error("导入失败",e);throw new RuntimeException("导入失败");}return list;}/*** EXCEL注解的字段* @param tClass* @return* @param <T>*/public static<T> String[] getAllIsExcelFields(Class<T> tClass) {try{ArrayList<String> strings = new ArrayList<>();Field[] declaredFields = tClass.getDeclaredFields();for (Field declaredField : declaredFields) {declaredField.setAccessible(true);if(declaredField.isAnnotationPresent(Excel.class)){Excel annotation = declaredField.getAnnotation(Excel.class);strings.add(annotation.name());}}String[] allIsExcelFields = strings.toArray(new String[strings.size()]);return allIsExcelFields;}catch (Exception e){log.error("获取所有标注了EXCEL注解的字段异常",e);}return null;}public static <T> List<T> importExcelBatch(File file, Integer sheetNun, Class<T> pojoClass, String[] templateFields) {ImportParams params = new ImportParams();params.setTitleRows(0);params.setHeadRows(1);//开始位置params.setStartSheetIndex(sheetNun);//数量params.setSheetNum(1);params.setImportFields(templateFields);return  importExcelExcep(file, pojoClass, params);}
}
//也可以进行文件校验-----写到service即可,或者抽取到一个工具类中private void checkFile(MultipartFile file) {// 检查文件是否为空if (file == null || file.isEmpty()) {//上传文件为空 --异常,可自行定义throw new BizException(BizError.UPLOAD_FILE_EMPTY_ERROR.getMsg());}// 检查文件类型(支持 xlsx、xlsb、xlsm、xls、xlst)String fileName = file.getOriginalFilename();if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xlsb") && !fileName.endsWith(".xlsm") && !fileName.endsWith(".xls") && !fileName.endsWith(".xlst")) {//文件格式异常-----抛出异常可自行定义throw new BizException(BizError.IMP_IMPORT_FILE_TYPE_ERROR.getMsg());}}

结果:

在这里插入图片描述


相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • JAVA8中的Stream API是什么及其用法
  • 数据结构(二叉树-2)
  • TCP/IP的三次握手和四次握手
  • 【MetaGPT系列】【MetaGPT完全实践宝典——多智能体实践】
  • 【Opencv】色彩空间 color space
  • CSS布局:左侧一个固定元素, 右侧元素数量不定, 要求右侧元素数量多时直接另起一行, 左侧元素单独一行
  • vscode搭建rust开发环境
  • 【Langchain大语言模型开发教程】评估
  • 数据集相关类代码回顾理解 | utils.make_grid\list comprehension\np.transpose
  • C++实用指南:Lambda 表达式的妙用
  • C#中的字符串
  • vue3前端开发-小兔鲜项目-使用pinia插件完成token的本地存储
  • 推荐一款前端滑动验证码插件(Vue、uniapp)
  • C++设计模式--单例模式
  • Java人力资源招聘社会校招类型招聘系统PC端
  • $translatePartialLoader加载失败及解决方式
  • Apache Pulsar 2.1 重磅发布
  • el-input获取焦点 input输入框为空时高亮 el-input值非法时
  • IDEA常用插件整理
  • Laravel5.4 Queues队列学习
  • orm2 中文文档 3.1 模型属性
  • spring + angular 实现导出excel
  • 程序员最讨厌的9句话,你可有补充?
  • 可能是历史上最全的CC0版权可以免费商用的图片网站
  • 聊聊springcloud的EurekaClientAutoConfiguration
  • 前端设计模式
  • 使用putty远程连接linux
  • 与 ConTeXt MkIV 官方文档的接驳
  • 正则表达式小结
  • ​Kaggle X光肺炎检测比赛第二名方案解析 | CVPR 2020 Workshop
  • ​ssh免密码登录设置及问题总结
  • $.each()与$(selector).each()
  • (Java岗)秋招打卡!一本学历拿下美团、阿里、快手、米哈游offer
  • (Matlab)使用竞争神经网络实现数据聚类
  • (NSDate) 时间 (time )比较
  • (vue)el-cascader级联选择器按勾选的顺序传值,摆脱层级约束
  • (补充)IDEA项目结构
  • (超详细)语音信号处理之特征提取
  • (附源码)springboot 基于HTML5的个人网页的网站设计与实现 毕业设计 031623
  • (回溯) LeetCode 46. 全排列
  • (简单) HDU 2612 Find a way,BFS。
  • (源码版)2024美国大学生数学建模E题财产保险的可持续模型详解思路+具体代码季节性时序预测SARIMA天气预测建模
  • (转)【Hibernate总结系列】使用举例
  • (转)VC++中ondraw在什么时候调用的
  • (转)菜鸟学数据库(三)——存储过程
  • (转)母版页和相对路径
  • (自适应手机端)行业协会机构网站模板
  • .mkp勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .net core 6 集成 elasticsearch 并 使用分词器
  • .net 连接达梦数据库开发环境部署
  • .NET6 开发一个检查某些状态持续多长时间的类
  • .NET上SQLite的连接
  • :如何用SQL脚本保存存储过程返回的结果集
  • @CacheInvalidate(name = “xxx“, key = “#results.![a+b]“,multi = true)是什么意思
  • [ vulhub漏洞复现篇 ] ThinkPHP 5.0.23-Rce