Easys Excel的表格导入(读)导出(写)-----java

news2024/10/7 14:28:31

一,EasyExcel官网:

可以学习一些新知识:

EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy Excel

二,为什么要使用easyexcle

excel的一些优点和缺点

java解析excel的框架有很多 :

poi jxl,存在问题:非常的消耗内存,

easyexcel 我们遇到再大的excel都不会出现内存溢出的问题 能够将一个原本3M excel文件,poi来操作将会占用内存

100MB,使用easyexcel减低到几Mb,使用起来更加简单

poi读 1、创建xsshworkbook/hssfworkbook(inputstream in)

2、读取sheet

3、拿到当前sheet所有行row

4、通过当前行去拿到对应的单元格的值


easyexcel拟解决的问题

1.excel读写时内存溢出

2.使用简单

3.excel格式解析


工作原理

三,项目的步骤

依赖包:

基本上要用的的依赖包:

       <!--		mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--	mysql	-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.28</version>
        </dependency>
        <!--        reds依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
        </dependency>
        <!--     连接池依赖   -->
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>
        </dependency>
<!--        数据池-->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>
<!--    mapper    -->
        <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.0.2</version>
        </dependency>

        <!--    easyexcel依赖    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

一,导出(写)流程写法:

1. Server接口:

package com.example.excel01.generator.service;

import com.example.excel01.generator.domain.Excel;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
* @author zeng
* @description 针对表【excel】的数据库操作Service
* @createDate 2023-08-02 11:10:56
*/
public interface ExcelService extends IService<Excel> {
    public Integer getCount(); //总条数
    public List<Excel> getListBYPage(Integer pageOn); //分页查询

}

2. 2.ServiceImpl类:

package com.example.excel01.generator.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.excel01.generator.domain.Excel;
import com.example.excel01.generator.mapper.ExcelMapper;
import com.example.excel01.generator.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author zeng
* @description 针对表【excel】的数据库操作Service实现
* @createDate 2023-08-02 11:10:56
*/
@Service
@Transactional
public class ExcelServiceImpl extends ServiceImpl<ExcelMapper, Excel>
    implements ExcelService {
    @Autowired
    private ExcelMapper excelMapper;
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Integer getCount() {
        return excelMapper.selectCount(null);
    }
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<Excel> getListBYPage(Integer pageOn) {
        Integer begin=(pageOn-1)*50000+1;
        //第几页显示多少数据
        return excelMapper.ListPage(begin,50000);
    }
}

3. 3.Test测试:

    /**
     * 写数据
     * */
    @Test
    void contextLoads4(){
        //保存路径
        String path="E:\\aaa\\ciy2.xls";
        //查询数据总条数
        Integer count = excelService.getCount();
        //创建easyexcel的写出类构造器 参数 告诉构造器 我的excel将来要写到哪里 以及excel中数据是基于哪个java对象模板创建的
        ExcelWriter excelWriter = EasyExcel.write(path, Excel.class).build();
        //判断一页能放多少条数据
        Integer sheetNum = count % 50000 == 0 ? count / 50000 : count / 50000 + 1;
        log.info("sheetNum=={}",sheetNum);
        for(int i=1;i<sheetNum;i++){
            log.info("第"+i+"批次");
            //分页查询数据库
            List<Excel> listPage = excelService.getListBYPage(i);
            //创建sheet构造器
            WriteSheet sheet = EasyExcel.writerSheet("test").build();
            //使用excel对象将数据写入到创建的sheet当中
            excelWriter.write(listPage,sheet);
        }
        excelWriter.finish();
        log.info("导出成功");
    }

二,导入(读)流程写法

1. 监听器:

读取数据要通过监听器来实现,监听读取的每一条数据:


监听器:

package com.example.excel01.generator.listenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.excel01.generator.domain.FmAddress;
import com.example.excel01.generator.service.FmAddressService;
import lombok.extern.slf4j.Slf4j;

/**
 * 监听器
 */

@Slf4j
public class EasyExcelListenner extends AnalysisEventListener<FmAddress> {

    static Integer a = 0;

    @Override
    public void invoke(FmAddress fmAddress, AnalysisContext analysisContext) {
        ++a;
        log.info("a={}",a);
        if (a == 1000) {
            try {
                a=0;
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        log.info(String.valueOf(fmAddress));
        //获取bean
        FmAddressService fmAddressService = SpringJobBeanFactory.getBean(FmAddressService.class);
        fmAddressService.insert(fmAddress);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}

a. 知识点普及:

1.监听器我们是继承Excel中的AnalysisEventListener方法来

2.该监听器是不被Spring (bean) 容器管理的,我要手动注入容器


2. 手动将监听器注入Spring容器:

package com.example.excel01.generator.listenner;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @ClassName: SpringJobBeanFactory*/
@Component
public class SpringJobBeanFactory implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringJobBeanFactory.applicationContext=applicationContext;

    }
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T>  name) throws BeansException {
        if (applicationContext == null){
            return null;
        }
        return applicationContext.getBean(name);
    }
}

a. 普及知识点:

手动注入bean 调用的是ApplicationContextAware接口


3.Test测试类:

    /**
     * 读数据
     */
    @Test
    void contextLoads5(){
        //保存路径
        String path="E:\\aaa\\ciy.xls";
        ExcelReader build = EasyExcel.read(path, FmAddress.class, new EasyExcelListenner()).build();
        ReadSheet build1 = EasyExcel.readSheet(0).build();
        log.info("build1={}",build1);
        build.read(build1);
        build.finish();

    }

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

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

相关文章

使用TDOSCommand调用Powershell脚本对进程进行操作

列出当前运行的进程&#xff1a; varPowerShellPath, ScriptPath, CommandLine: string; beginMemo6.Clear;PowerShellPath : powershell.exe ; // 假设 PowerShell 可执行文件在系统环境变量中// 构造命令行参数CommandLine : Get-Process | Select-Object Name,Id;// 设置命…

【Linux】总结2-进程篇1

文章目录 冯诺伊曼结构操作系统什么是程序&#xff1f;什么是进程&#xff1f;操作系统是如何来管理进程的&#xff1f;PCB&#xff08;struct task_struct{...}&#xff09; 冯诺伊曼结构 冯诺依曼提出了计算机制造的三个基本原则&#xff0c;即采用二进制逻辑、程序存储执行…

Stable Diffusion - 常用的负向提示 Embeddings 解析与 坐姿 (Sitting) 提示词

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/132145248 负向 Embeddings 是用于提高 StableDiffusion 生成图像质量的技术&#xff0c;可以避免生成一些不符合预期的图像特征&#xff0c;比如…

day5gdb调试模式和makefile

一、gdb调试 1.1gdb调试的作用 gdb调试检查的是逻辑错误&#xff0c;而非语法错误 1.2gdb流程 1、gcc -g 1.c ---->加-g参数的作用&#xff0c;生成可以调试的gdb文件 2、gdb 可执行文件名/a.out ---->进入gdb工具进行调试 3、输入l&#xff0c;带行号打印文件信息…

管理类联考——逻辑——论证逻辑——汇总篇——目录+提炼

文章目录 一、削弱方法关系的削弱必要方法的削弱因果推理的削弱果因推理的削弱概念跳跃的削弱数量比例的削弱比例因果的削弱 二、支持方法关系的支持必要方法的支持因果推理的支持果因推理的支持概念跳跃的支持数量比例的支持比例因果的支持 三、假设方法关系的假设必要方法的假…

不分股权不分管理,只分利润:共享模式的新零售布局

实体行业如何通过共享模式去整合那些有资源的人&#xff0c;来完成新零售的一个布局&#xff1f;比如对于餐饮行业而言&#xff0c;一样的资源&#xff0c;经常有用餐、聚餐需求的人是谁&#xff1f; 有商会组织者、公司的管理层、培训机构、社群群主等等。那么如何把这些人整…

记一次Linux启动Mysql异常解决

文章目录 第一步&#xff1a; netstat -ntlp 查看端口情况2、启动Mysql3、查看MySQL日志 tail -100f /var/log/mysqld.log4、查看磁盘占用情况&#xff1a;df -h5、思路小结 第一步&#xff1a; netstat -ntlp 查看端口情况 并没有发现3306数据库端口 2、启动Mysql service …

【Windows】Windows11系统用户自己添加开机启动项的方法

按win R快捷键&#xff0c;打开运行窗口&#xff0c;在输入框中输入shell:startup后点击运行&#xff0c;打开启动文件夹&#xff1a; 把想增加的开机启动软件的快捷方式图标拖入到该文件夹中&#xff0c;如下图所示&#xff1a; 按ctrl shift esc打开任务管理器&#xff0c…

UWB伪应用场景 - 别再被商家忽悠

近几年UWB技术在网上宣传得如火如荼&#xff0c;与高精度定位几乎或等号&#xff0c;笔者认为这是营销界上的一大成功案例。 UWB超宽带技术凭借着低功耗、高精度&#xff0c;确实在物联网行业混得风生水起&#xff0c;但在无数实际应用案例中&#xff0c;根据客户的反馈情况&a…

python小游戏代码200行左右,python小游戏代码1000行

大家好&#xff0c;小编为大家解答20行python代码的入门级小游戏的问题。很多人还不知道python小游戏代码200行左右&#xff0c;现在让我们一起来看看吧&#xff01; 大家小时候都玩过贪吃蛇吧&#xff1f;小编小时候可喜欢拿爸妈的手机玩了&#xff0c;厉害着呢&#xff01;今…

Spring-2-深入理解Spring 注解依赖注入(DI):简化Java应用程序开发

今日目标 掌握纯注解开发依赖注入(DI)模式 学习使用纯注解进行第三方Bean注入 1 注解开发依赖注入(DI)【重点】 问题导入 思考:如何使用注解方式将Bean对象注入到类中 1.1 使用Autowired注解开启自动装配模式&#xff08;按类型&#xff09; Service public class StudentS…

redis基础(三十六)

安装redis、配置redis 目录 一、 概述 &#xff08;一&#xff09;NoSQL 1、类型 2、应用场景 &#xff08;二&#xff09;Redis 二、安装 &#xff08;一&#xff09;编译安装 &#xff08;二&#xff09;RPM安装 三、目录结构 四、命令解析 五、redis登录更改 1、…

三层交换实验

前言 在实际的企业应用中&#xff0c;我们会先建立不同的vlan把用户先隔开来。然后再通过三次交换机技术打通vlan直接的网络。 这样的目的如下&#xff1a; 隔离&#xff1a; 隔离是广播域&#xff0c;也就是隔离的是故障连通&#xff1a; 连通的是正常的通信 比如校园网&am…

在魔塔社区搭建通义千问-7B(Qwen-7B)流程

复制以下语句 python3 -m venv myvenvsource myvenv/bin/activatepip install modelscope pip install transformers_stream_generator pip install transformers pip install tiktoken pip install accelerate pip install bitsandbytestouch run.py vi run.py复制下面代码粘…

IMV5.0

背景内容&#xff1a; 经历了多个版本&#xff0c;基础内容在前面&#xff0c;可以使用之前的基础环境&#xff1a; v1&#xff1a; https://blog.csdn.net/wtt234/article/details/132139454 v2&#xff1a; https://blog.csdn.net/wtt234/article/details/132144907 v3&#…

04-8_Qt 5.9 C++开发指南_QTableWidget的使用

文章目录 1. QTableWidget概述2. 源码2.1 可视化UI设计2.2 程序框架2.3 qwintspindelegate.h2.4 qwintspindelegate.cpp2.5 mainwindow.h2.6 mainwindow.cpp 1. QTableWidget概述 QTableWidget是Qt中的表格组件类。在窗体上放置一个QTableWidget 组件后,可以在 PropertyEditor…

二、 MySQL 内部技术架构

二、 MySQL 内部技术架构 047 Mysql内部支持缓存查询吗&#xff1f; 当MySQL接收到客户端的查询SQL之后&#xff0c;仅仅只需要对其进行相应的权限验证之后&#xff0c;就会通过Query Cache来查找结果&#xff0c;甚至都不需要经过Optimizer模块进行执行计划的分析优化&…

产品缺陷管理软件:了解功能与选择要点

在现代社会&#xff0c;产品缺陷管理软件已经成为了各个行业必不可少的工具。它可以帮助企业更好地管理和解决产品中存在的缺陷问题&#xff0c;提高产品质量和客户满意度。然而&#xff0c;市场上存在着众多的产品缺陷管理软件&#xff0c;如何选择一款好用、适合自己的软件成…

Java实现数字加密

Java实现数字加密 需求分析代码实现小结Time 需求分析 1.首先&#xff0c;考虑方法是否需要接收数据处理&#xff1f; 需要一个4位数&#xff0c;至于是哪一个数&#xff0c;让方法的调用者传递。 所以&#xff0c;方法的参数&#xff0c;就是这个需要加密的四位数 2.接着&…

Unity 编辑器资源导入处理函数 OnPostprocessAudio :深入解析与实用案例

Unity 编辑器资源导入处理函数 OnPostprocessAudio 用法 点击封面跳转下载页面 简介 在Unity中&#xff0c;我们可以使用编辑器资源导入处理函数&#xff08;OnPostprocessAudio&#xff09;来自定义处理音频资源的导入过程。这个函数是继承自AssetPostprocessor类的&#xff…