使用EasyExcel实现Excel的导入、导出、下载模板等功能

文章目录

  • 导入功能
    • 依赖
    • 实体类
    • 监听器
    • 控制器
    • 批量插入
  • 导出功能
  • 下载模板
    • 实体类
    • 控制层
    • 业务层

参考:https://blog.csdn.net/z845910508/article/details/123679054

导入功能

依赖

在项目的pom文件导入easyexcel的依赖:

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>easyexcel</artifactId>
			<version>2.1.1</version>
		</dependency>

实体类

创建与数据库表对应的实体类,并且添加与excel表头对应的注解@ExcelProperty ,要记得修改下面index的值:value对应excel的表头字段名称,index为表头顺序

import com.alibaba.excel.annotation.ExcelProperty;

import lombok.Data;

@Data
public class Entity {
	//这里的value对应excel的表头字段名称,index为表头顺序
    @ExcelProperty(value = "名称1",index = 0)
    private String name1;
    @ExcelProperty(value = "名称2",index = 1)
    private String name2;
}

监听器

//监听器
public class ExcelListener extends AnalysisEventListener<Entity> {
    MyService myService;
    List<Entity> list = new ArrayList<>();
    public  ExcelListener (MyService myService){
        this.myService= myService;
    }

    //读取除表头外的每行数据执行该方法
    @Override
    public void invoke(Entity entity, AnalysisContext context) {
        list.add(entity);
    }
    
    //读取结束执行该方法
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //把与数据库重复的数据删除
        List<Entity> entityList = myService.queryListByExcel(list);
        for (Entity entity : entityList ) {
            list.remove(entity);
        }
		//保存到数据库中
        myService.saveList(list);
    }
}

控制器

	//控制器
    @PostMapping("/import")
    @ApiOperation("数据导入")
    public String easyExeclImport(@RequestParam(value = "file") MultipartFile file) throws IOException {
         InputStream inputStream = file.getInputStream();
         //service要通过参数传进去
         EasyExcel.read(inputStream, Entity.class, new NbqExcelListener(myService)).sheet().doRead();
       return "success";
    }

批量插入

示例

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.demo.mapper.MedicnesMapper">
    <insert id="saveMedicnesList" parameterType="cn.demo.entity.Medicnes">
        insert into medices
        (food,remark)
        values
        <foreach collection="list" item="rm" separator=",">
            (#{rm.food},#{rm.remark})
        </foreach>
    </insert>
</mapper>

导出功能

EasyExcel实现Excel文件导入导出
easyexcel导出
EasyExcel导出详解

使用EasyExcel实现Excel的导入、导出、下载模板等功能_第1张图片

    public static void main(String[] args) {
        String filename = "D:\\linshi\\excel\\test1.xlsx";
        //准备要写入excel的数据
        List<TerminalEntity> list = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            TerminalEntity entity = new TerminalEntity();
            entity.setImei(i + "");
            entity.setCustomer("customer");
            list.add(entity);
        }
        // 向Excel中写入数据
        EasyExcel.write(filename, TerminalEntity.class)
                .sheet("终端信息")
                .doWrite(list);
    }

下载模板

实体类

@Data
public class TerminalInfoExcelBean {
    @ExcelProperty(value = "IMEI",index = 0)
    private String imei;
    @ExcelProperty(value = "TYPE",index = 1)
    private String type;
    @ExcelProperty(value = "VENDOR",index = 2)
    private String vendor;
}

控制层

    @ApiOperation("下载Excel模板")
    @RequestMapping(value = "/downloadExcel",method = RequestMethod.GET)
    public CommonResult<String> easyExcelDownload(HttpServletResponse response) throws IOException {

        slaTerminalMonitorService.easyExcelDownload(response);

        return CommonResult.success(null, "下载Excel模板成功!");
    }

业务层

    /**
     * 下载excel模板
     * @param response
     */
    public void easyExcelDownload(HttpServletResponse response) throws IOException {

        List<TerminalInfoExcelBean> list = new ArrayList<>();
        TerminalInfoExcelBean bean = new TerminalInfoExcelBean();
        bean.setImei("111");
        bean.setType("摄像头");
        bean.setModel("C920");

        list.add(bean);

        // 这里URLEncoder.encode可以防止中文乱码 easyexcel没有关系
        String fileName = URLEncoder.encode("数据表格模板", "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), TerminalInfoExcelBean.class).sheet("模板").doWrite(list);
    }

你可能感兴趣的:(技能学习,EasyExcel,Excel导入与导出)