springboot+easypoi导入导出excel表

本文介绍了如何在springboot项目中利用easypoi库进行Excel数据的导入导出。首先,讲解了导出数据的步骤,包括添加依赖、在实体类中使用@Excel注解以及编写控制类。接着,详细说明了导入数据的过程,特别是当实体类包含对象属性时,如何处理并重写equals和hashcode方法,以及如何处理非空字段的注解。最后,展示了部分实体类和控制类的代码片段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot+easypoi导入导出excel数据

1.导出数据

导入依赖

        <!--easypoi依赖(表格导入导出)-->
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-spring-boot-starter</artifactId>
            <version>4.3.0</version>
        </dependency>

对需要操作的表格的实体类加上注解,全部属性都加上@Excel注解

    //Employee实体类中

	@Excel(name = "员工姓名")
    private String name;

    @Excel(name = "性别")
    private String gender;

	//如果有时间类属性,可以用format格式化一下,width设置长度
    @Excel(name = "出生日期",width = 20,format = "yyyy-MM-dd")
    private LocalDate birthday;
	
	//如果有对象属性,则需要换成@ExcelEntity注解
    @ExcelEntity(name = "部门")
    private Department department;

在标注了@ExcelEntity属性的实体类中,在需要获取该对象的某个属性上 加上@Excel注解

    //Department实体类中

	@Excel(name = "部门")
    private String name;

控制类

@GetMapping(value = "/export",produces = "application/octet-stream")
public void exportEmployee(HttpServletResponse response){
    //获取所有员工数据
    List<Employee> list = employeeService.getEmployee(null);
    //三个参数,导出标题名,sheetname,文件格式 HSSF:xsl  XSSH:xslx
    ExportParams params = new ExportParams("员工表", "员工表", ExcelType.HSSF);
    Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
    //以流的形式导出
    ServletOutputStream outputStream = null;
    try {
        //流形式
        response.setHeader("content-type","application/octet-stream");
        //防止中文乱码
        response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
        outputStream = response.getOutputStream();
        workbook.write(outputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (null != outputStream){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
2.导入数据

如果不含有实体类对象属性,直接直接跳到下面编写控制类即可

如果要导出的实体类含有对象属性,就相对麻烦一点

这里我重写equals和hashcode方法来快速找到对象属性的id(因为数据库一般不会存对象,对象属性只是方便我们业务实现,并不会真实写入数据库,一般都拥有另一个属性—实体类对象的id)

Employee实体类:

	//Employee实体类中有这样两个属性  部门id  和部门实体类对象
    private Integer departmentId;
    
    @TableField(exist = false)
    @ExcelEntity(name = "部门")
    private Department department;

Department实体类:

加上lombok直接

@NoArgsConstructor
@RequiredArgsConstructor	//有参构造
@EqualsAndHashCode(callSuper = false,of = "name")

导入的数据一般是部门名称,所以在name属性再加上一个注解@NonNull,表示该属性在有参构造方法中不能为空,其他没加这个注解的属性可以为空

@Excel(name = "部门")
@NonNull
private String name;

控制类

如果不含有实体类对象属性,忽略foreach循环

@PostMapping("/import")
public Result importEmployee(MultipartFile file){
    ImportParams params = new ImportParams();
    //去掉第一行标题
    params.setTitleRows(1);
    List<Nation> nationList = nationService.list();
    List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
    List<Department> departmentList = departmentService.list();
    List<Joblevel> joblevelList = joblevelService.list();
    List<Position> positionList = positionService.list();

    try {
        //从输入流中拿到employee的list数据
        List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
        
        
        //如果没有对象属性,下面这个foreach循环就跳过
        list.forEach(employee->{
            //各个实体类都重写equals和hashCode方法,只要name属性的值一致就表示对象一致
            //获取并设置民族id
            employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
            //获取并设置政治面貌id
            employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
            //获取并设置部门id
            employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
            //获取并设置职称id
            employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
            //获取并设置职位id
            employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
        });
        
        
        //批量插入
        if (employeeService.saveBatch(list)){
            return Result.success("导入成功");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Result.error("导入失败");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值