Implementing Excel Import and Export with Spring Boot, MyBatis-Plus, and EasyExcel

Start by creating a Spring Boot project and add the necessary dependencies to the pom.xml file.

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.33</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.16</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.3.2</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

Configure MyBatis-Plus in application.yml.

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo_db?useSSL=false&serverTimezone=UTC
    username: root
    password: your_password

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true

Create a Mapper interface that extends BaseMapper. Annotate it with @Mapper or use @MapperScan on the main application class.

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmployeeMapper extends BaseMapper<Employee> {
}

Define the entity class, mapping it to database fields and Excel columns using EasyExcel annotations.

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 com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;

@Data
@HeadRowHeight(25)
@ContentRowHeight(18)
public class Employee {
    @TableId(type = IdType.AUTO)
    @ExcelProperty(value = "Employee ID", index = 0)
    private Long id;

    @ExcelProperty(value = "Full Name", index = 1)
    private String name;

    @ExcelProperty(value = "Department", index = 2)
    private String department;

    @ExcelProperty(value = "Email Address", index = 3)
    private String email;

    @ExcelProperty(value = "Join Date", index = 4)
    private String joinDate;
}

Create a listener class for processing Excel rows. This clas manages batch insertion into the database.

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

@Slf4j
public class EmployeeDataListener implements ReadListener<Employee> {

    private static final int BATCH_SIZE = 100;
    private List<Employee> batchCache = ListUtils.newArrayListWithExpectedSize(BATCH_SIZE);
    private final EmployeeMapper employeeMapper;

    public EmployeeDataListener(EmployeeMapper mapper) {
        this.employeeMapper = mapper;
    }

    @Override
    public void invoke(Employee data, AnalysisContext context) {
        batchCache.add(data);
        if (batchCache.size() >= BATCH_SIZE) {
            persistBatch();
            batchCache = ListUtils.newArrayListWithExpectedSize(BATCH_SIZE);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        persistBatch();
        log.info("Excel parsing completed.");
    }

    private void persistBatch() {
        if (!batchCache.isEmpty()) {
            log.info("Persisting {} records.", batchCache.size());
            for (Employee emp : batchCache) {
                employeeMapper.insert(emp);
            }
        }
    }
}

Implement the controlller with endpoints for data retrieval, file upload (import), and file download (export).

import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

    @Autowired
    private EmployeeMapper employeeMapper;

    @GetMapping
    public List<Employee> getAllEmployees() {
        return employeeMapper.selectList(null);
    }

    @PostMapping("/import")
    public String importEmployees(@RequestParam("file") MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),
                Employee.class,
                new EmployeeDataListener(employeeMapper))
                .sheet()
                .doRead();
        return "Import successful";
    }

    @GetMapping("/export")
    public void exportEmployees(HttpServletResponse response) throws IOException {
        List<Employee> employeeList = employeeMapper.selectList(null);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("Employee_List", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Employee.class).sheet("Employees").doWrite(employeeList);
    }
}

Ensure the database table field names match the entity's property names or use @TableField for explicit mapping. Avoid using special characters like underscores that might conflict with ORM mapping conventions without proper annotation.

Tags: Spring Boot mybatis-plus EasyExcel Excel Import Excel Export

Posted on Fri, 31 Jul 2026 16:30:07 +0000 by [ArcanE]