使用easypoi读取Excel模板

news2024/9/16 19:13:31
  • 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 {
    @Autowired
    private 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 {
    @Autowired
    private 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 {
    @Autowired
    private 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 {
    @Autowired
    private LossComputeService lossComputeService;


    public AjaxResult<LossCalculationLog> importExcel(File file) {
        //文件进行校验
//        checkFile(file);
        //获取所有字段名称
        String[] allIsExcelFields = EasyExcelUtil.getAllIsExcelFields(TestDto.class);
        System.out.println("获取的所有的字段名称"+allIsExcelFields.toString());
        //获取list字段sheet0
        List<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());
        }
    }

结果:

在这里插入图片描述


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1960951.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

OV SSL证书申请指南

OV SSL证书除了验证域名所有权外还需要验证组织信息&#xff0c;这类证书适用于对公司官网、品牌、安全性等有较高程度要求的企业级用户。具体申请流程如下&#xff1a; 一 、注册账号 注册账号填写230919注册码即可获得大额优惠券和全程一对一技术支持https://www.joyssl.co…

网页速度如何优化?从10s到0.5s

如何排除网页速度慢的故障&#xff1f; 优化运行缓慢的网页涉及多个层面的改进&#xff0c;可分为硬件、前端和后台优化。下面是一份全面的指南&#xff1a; 01 硬件优化 服务器资源 升级服务器&#xff1a;确保服务器能为流量提供足够的资源&#xff08;CPU、内存、带宽等&a…

【Windows】Mountain Duck(FTP服务器管理工具)软件介绍

软件介绍 Mountain Duck是一款基于Cyberduck开发的应用程序&#xff0c;它允许用户通过FTP、SFTP、WebDAV、S3和OpenStack Swift等协议连接到云存储和远程服务器&#xff0c;并在本地文件浏览器中以熟悉的方式访问和管理这些文件。 功能特点 支持多种协议: Mountain Duck支持…

右键没有压缩选项

想压缩文件选中右键没有压缩选项。 打开任意rar文件 选择选项-》设置&#xff0c;添加到winrar到开始菜单即可

HTML+CSS+JavaScript实现烟花绽放的效果源码

源码 复制粘贴代码 在同级别下放一张图片fire.png接可以了 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><…

AI多模态模型架构之输出映射器:Output Projector

〔探索AI的无限可能&#xff0c;微信关注“AIGCmagic”公众号&#xff0c;让AIGC科技点亮生活〕 本文作者&#xff1a;AIGCmagic社区 刘一手 前言 AI多模态大模型发展至今&#xff0c;每年都有非常优秀的工作产出&#xff0c;按照当前模型设计思路&#xff0c;多模态大模型的…

QChart笔记6:显示点的值、显示点坐标值

在QChart笔记2: 添加鼠标悬停显示和格式处理_qchart 折线图 响应鼠标显示数据-CSDN博客上修改而来。 在笔记2中&#xff0c;通过鼠标悬停的方式显示了坐标轴Y的值&#xff0c;如果要一直显示应该怎么写呢&#xff1f;比如要达到下面的效果。 核心是这句&#xff1a; series1-…

Windows10安装——制作U盘启动盘(保姆级)

安装前准备&#xff1a; 一个不少于8G的U盘&#xff0c; 一个可以上网的windows电脑&#xff1b; 第一步&#xff1a;安装启动盘制作工具 首先我们下载启动盘制作工具&#xff0c; 官网网址&#xff1a;下载 Windows 10 (microsoft.com)&#xff1b; 百度网盘下载&#xf…

赛氪网受邀参加中国国际科技促进会第五届第五次常务理事扩大会议

2024年7月27日&#xff0c;环球赛乐&#xff08;北京&#xff09;科技有限公司&#xff08;以下简称“赛氪网”&#xff09;受邀参加了中国国际科技促进会第五届第五次常务理事扩大会议。此次会议汇聚了众多科技界的精英和专家&#xff0c;共同探讨科技发展的新方向&#xff0c…

【Mybatis】xml 配置文件

Mybatis的开发有两种方式&#xff1a; 注解XML 使用Mybatis的注解方式&#xff0c;主要是来完成一些简单的增删改查功能。 如果需要实现复杂的SQL功能&#xff0c;建议使用XML来配置映射语句&#xff0c;也就是将SQL语句写在XML配置文件中。在Mybatis中使用XML映射文件方式开…

Cxx primer-chap10-Generic Algorithms

generic algorithms的解释&#xff1a;&#xff0c;具体而言iterator使得算法与容器类型无关&#xff1a;&#xff0c;但算法的实现成功与否有时依赖于&#xff08;element type&#xff09;元素类型&#xff1a;通用算法的实现依赖于iterator&#xff0c;具体而言algorithm –…

python windows环境部署

在官网安装www.python.org linux系统的只能编译安装 windows的可以直接安装 这里是windows安装 .3.9.6版本 一直下一步就可以&#xff0c;然后鼠标右键在按住shift用终端打开 输入py或者python验证一下是否安装成功 打开目录文件夹 在里面新建一下pip的文件夹&#xff0c;里…

OpenAI开发了一种新方法来教授AI模型与安全政策保持一致

OpenAI 宣布了一种新的方法来教授人工智能模型与安全政策保持一致&#xff0c;这种方法被称为"基于规则的奖励"&#xff08;Rules Based Rewards&#xff09;。据 OpenAI 安全系统负责人 Lilian Weng 介绍&#xff0c;基于规则的奖励&#xff08;RBR&#xff09;可以…

【研发日记】Matlab/Simulink技能解锁(十一)——Stateflow中的en、du、ex应用对比

文章目录 前言 项目背景 en类型 du类型 ex类型 组合类型 分析和应用 总结 参考资料 前言 见《【研发日记】Matlab/Simulink技能解锁(六)——六种Simulink模型架构》 见《【研发日记】Matlab/Simulink技能解锁(七)——两种复数移相算法》 见《【研发日记】Matlab/Simul…

盘点适合新手使用的4个剪辑工具。

很多宝子们都觉得剪辑很难&#xff0c;想学习又觉得自己没有专业的剪辑知识指导&#xff0c;不好上手。那是因为不知道有这些工具&#xff0c;这4款专业的剪辑软件对新手来说简直就是福音。 1、福昕剪辑 直达链接&#xff1a;www.pdf365.cn/foxit-clip/ 这个软件的界面设置的…

cGDB 调试方法

用法总结 Ubuntu系统&#xff0c;安装cGDB sudo apt updatesudo apt install cgdb 编译代码 g -g -o example example.cpp -lpthread要确保有 -g &#xff0c;代码是调试信息编译的 启动测试&#xff1a;cgdb ./可执行文件 此处可以使用esc进入命令模式&#xff0c;vim命令上下…

生活方式酒店升势迅起,喆啡酒店缘何成为投资热点?

伴随国内消费结构转型升级&#xff0c;旅游需求持续增加。文旅部发布的《国内旅游提升计划&#xff08;2023—2025年&#xff09;》提出&#xff0c;需丰富优质旅游供给&#xff0c;并进一步提高消费者体验及满意度&#xff0c;这将为酒店行业带来更广阔的客源和更高的质量要求…

SpringBoot上传超大文件导致OOM,完美解决办法

问题描述 上传大文件报错: Caused by: java.lang.OutOfMemoryError at java.io.ByteArrayOutputStream.hugeCapacity(ByteArrayOutputStream.java:123) ~[?:1.8.0_381] at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:117) ~[?:1.8.0_381] …

探索Axure在数据可视化原型设计中的无限可能

在当今数字化浪潮中&#xff0c;产品设计不仅关乎美观与功能的平衡&#xff0c;更在于如何高效、直观地传达复杂的数据信息。Axure RP&#xff0c;作为原型设计领域的佼佼者&#xff0c;其在数据可视化原型设计中的应用&#xff0c;正逐步揭开产品设计的新篇章。本文将从多个维…