使用easyexcel进行excel的导入和导出(web)

前言:使用springboot,mybatis,excel3.x.x,通用mapper。本文主要演示怎么使用easyexcel,因此先展示效果图,方便读者判断本文是否是自己需要的。源码demo在文末,需要者自取。

导出excel

image-20220429230020168

导入excel

image-20220429230158233

现在正式演示怎么使用easyexcel进行excel的导入导出。

1.准备工作

  • 导入依赖
<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.0.5</version>
</dependency>
<dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.0.2</version>
</dependency>
  • 配置application.yml,连接数据库即可

  • 数据库实体类

package cn.homyit.domain;

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 lombok.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ContentRowHeight(18)//内容行高
@HeadRowHeight(25)//标题行高
@ColumnWidth(20)//列宽,可设置成员变量上
public class Applicant {

  @ExcelProperty(index = 0,value = "申请人id")//index表示第几列,value表示标题
  private String id;

  @ExcelProperty(index = 1,value = "申请人名字")
  private String name;

  @ExcelProperty(index = 2,value = "申请人学号")
  private String number;

  @ExcelProperty(index = 3,value = "班级")
  private String classs;

  @ExcelProperty(index = 4,value = "邮箱")
  private String mail;

  @ExcelIgnore//不进行导入
  private String introduction;
}

  • sql (从前的小玩意,干脆就用了)

CREATE DATABASE `welcome` 
USE `welcome`;
DROP TABLE IF EXISTS `applicant`;
CREATE TABLE `applicant` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '名字',
`number` varchar(30) DEFAULT NULL COMMENT '学号',
`classs` varchar(50) DEFAULT NULL COMMENT '班级',
`mail` varchar(128) DEFAULT NULL COMMENT '邮箱',
`introduction` varchar(255) DEFAULT NULL COMMENT '自我介绍',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
insert  into `applicant`(`id`,`name`,`number`,`classs`,`mail`,`introduction`) values (2,'test','202026202015','计科一班','2750419070@qq.com',NULL),(3,'test','202026202020','计科一班计科一班','2750419070@qq.com',NULL),(4,'test','202026202025','计科一班','2750419070@qq.com',NULL),(5,'test','202026202055','计科一班','2750419070@qq.com',NULL),(6,'wwww','202026202088','计科一班','2750419070@qq.com',NULL),(7,'wwww','202026202087','计科一班','2750419070@qq.com',NULL),(8,'wwww','202026202098','v计科一班','2750419070@qq.com',NULL),(9,'wwww','202026202000','v计科一班','2750419070@qq.com',NULL),(10,'wwww','202026202001','计科一班','2750419070@qq.com',NULL),(11,'wwww','202026202011','计科一班','2750419070@qq.com',NULL);

2.导入到excel

2.1 使用httpresponse进行数据的响应

以下载的形式,controller调用service,为了直接可观,接口我就不展示,只给出实现接口类方法

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        applicantServiceService.download(response);
    }

2.2 service调用mapper

  @Override
    public void download(HttpServletResponse response) throws IOException {

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //设置响应内容类型
        response.setCharacterEncoding("utf-8");//编码
        String fileName = URLEncoder.encode("demo", "UTF-8").replaceAll("\\+", "%20");//设置文件名
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");//设置响应头

        List<Applicant> applicantByPage = getApplicantByPage(1);//第一页,获取第一页记录
        ExcelWriter writer = EasyExcel.write(response.getOutputStream(), Applicant.class).build();//获取写出流
        WriteSheet sheet = EasyExcel.writerSheet("one").build();//创建表格,设置表格页名称
        writer.write(applicantByPage,sheet);//读出
        writer.finish();//关闭流
    }

 @Override
    public List<Applicant> getApplicantByPage(Integer pageon) {
        int limit= 5;//页面容量
        Integer begin = (pageon-1)*limit;//起始记录
        return applicantMapper.selectByRowBounds(new Applicant(),
                new RowBounds(begin,limit));//
    }

2.3 mapper方法

package cn.homyit.mapper;

import cn.homyit.domain.Applicant;
import tk.mybatis.mapper.common.Mapper;

public interface ApplicantMapper extends Mapper<Applicant> {
}

启动即可成功下载excel啦!

3.导出到数据库

一样的调用,我就直接写了

 @PostMapping("/upload")
    public String upload(@RequestPart("file") MultipartFile file) throws IOException {
        applicantServiceService.upload(file);
        return "success";
 }
@Override
    public void upload(MultipartFile file) throws IOException {
        ExcelReader reader = EasyExcel.read(file.getInputStream(), Applicant.class, new EastExcelListener(applicantMapper)).build();//将applicantmapper传入
        ReadSheet sheet = EasyExcel.readSheet(0).build();//第一页
        reader.read(sheet);//读
        reader.finish();

    }

注意到这里使用了一个EastExcelListener监听器,这是我自定义的,如下

public class EastExcelListener extends AnalysisEventListener<Applicant> {

    private ApplicantMapper applicantMapper;

    public EastExcelListener(ApplicantMapper applicantMapper){
        this.applicantMapper =applicantMapper;
    }

    @Override
    public void invoke(Applicant applicant, AnalysisContext analysisContext) {
        applicantMapper.insert(applicant);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
       
    }
}

在读的时候,每读取excel一行记录就会调用监听器的invoke()方法,我们在此方法中进行数据插入到表。

注意到,为什么我这里的ApplicantMapper没有使用spring的注入呢?因为easyexcel使用监听器会有线程问题,所以我们采用构造方法传入mapper到监听器中。当然如果是无多线程操作,直接使用注入使用即可。

此时上传亦可成功。

链接:https://pan.baidu.com/s/1SBNXN6yLs-VvEZb594Ia_w?pwd=zhou
提取码:zhou

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐