Quick Start Guide to Using EasyExcel with Spring Boot 3 (Verified)

This tutorial walks through building a Spring Boot 3 project that integrates Alibaba's EasyExcel for Excel export and import, covering project structure, Maven dependencies, entity mapping, listener implementation, service and controller code, testing endpoints, and key Spring Boot 3 considerations such as Jakarta packages, JDK 17+, response header handling, memory management, and production‑grade best practices.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Quick Start Guide to Using EasyExcel with Spring Boot 3 (Verified)

EasyExcel is an Alibaba open‑source library for handling Excel files, suitable for export, import, large‑data read/write, and reducing Apache POI memory usage. This guide demonstrates a complete Spring Boot 3 demo using JDK 17, Maven, and a base package com.example.springboot.

1. Project Structure

springboot-easyexcel-demo
├─ pom.xml
├─ src/main/java/com/example/springboot
│  ├─ SpringbootApplication.java
│  ├─ controller/ExcelController.java
│  ├─ listener/UserExcelListener.java
│  ├─ model/UserExcelData.java
│  └─ service/ExcelService.java
└─ src/main/resources/application.yml

2. Add Maven Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

3. Main Application Class

package com.example.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}

4. Define Excel Entity

package com.example.springboot.model;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;

@Data
public class UserExcelData {
    @ExcelProperty("用户ID")
    private Long id;

    @ExcelProperty("用户名")
    private String username;

    @ExcelProperty("年龄")
    private Integer age;

    @ExcelProperty("邮箱")
    private String email;
}

Notes: @ExcelProperty("用户ID") defines the column header.

Fields are exported in the order they appear; use index to enforce a custom order.

5. Implement Import Listener

package com.example.springboot.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.example.springboot.model.UserExcelData;
import java.util.ArrayList;
import java.util.List;

public class UserExcelListener implements ReadListener<UserExcelData> {
    private final List<UserExcelData> dataList = new ArrayList<>();

    @Override
    public void invoke(UserExcelData data, AnalysisContext context) {
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("Excel读取完成,共 " + dataList.size() + " 条数据");
    }

    public List<UserExcelData> getDataList() {
        return dataList;
    }
}

6. Service Layer

package com.example.springboot.service;

import com.alibaba.excel.EasyExcel;
import com.example.springboot.listener.UserExcelListener;
import com.example.springboot.model.UserExcelData;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class ExcelService {
    public void exportUsers(HttpServletResponse response) throws IOException {
        List<UserExcelData> userList = mockData();
        String fileName = URLEncoder.encode("用户数据", StandardCharsets.UTF_8)
                .replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserExcelData.class)
                .sheet("用户列表")
                .doWrite(userList);
    }

    public List<UserExcelData> importUsers(MultipartFile file) throws IOException {
        UserExcelListener listener = new UserExcelListener();
        EasyExcel.read(file.getInputStream(), UserExcelData.class, listener)
                .sheet()
                .doRead();
        return listener.getDataList();
    }

    private List<UserExcelData> mockData() {
        List<UserExcelData> list = new ArrayList<>();
        UserExcelData user1 = new UserExcelData();
        user1.setId(1L);
        user1.setUsername("张三");
        user1.setAge(20);
        user1.setEmail("[email protected]");
        list.add(user1);
        UserExcelData user2 = new UserExcelData();
        user2.setId(2L);
        user2.setUsername("李四");
        user2.setAge(25);
        user2.setEmail("[email protected]");
        list.add(user2);
        return list;
    }
}

7. Controller

package com.example.springboot.controller;

import com.example.springboot.model.UserExcelData;
import com.example.springboot.service.ExcelService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {
    private final ExcelService excelService;

    public ExcelController(ExcelService excelService) {
        this.excelService = excelService;
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        excelService.exportUsers(response);
    }

    @PostMapping("/import")
    public List<UserExcelData> importExcel(MultipartFile file) throws IOException {
        return excelService.importUsers(file);
    }
}

8. Configuration (application.yml)

server:
  port: 8080

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

9. Testing the Application

9.1 Export

Visit http://localhost:8080/excel/export in a browser. The browser downloads 用户数据.xlsx with a sheet named 用户列表.

9.2 Import

POST http://localhost:8080/excel/import with multipart/form-data, field name file, containing an Excel file. Example header row:

用户ID | 用户名 | 年龄 | 邮箱
1     | 张三   | 20   | [email protected]
2     | 李四   | 25   | [email protected]

Response JSON example:

[
  {"id":1,"username":"张三","age":20,"email":"[email protected]"},
  {"id":2,"username":"李四","age":25,"email":"[email protected]"}
]

10. Spring Boot 3 Specific Considerations

10.1 Jakarta Packages

Spring Boot 3 uses Spring Framework 6, so javax.servlet classes are replaced by jakarta.servlet. Import jakarta.servlet.http.HttpServletResponse for file download.

10.2 JDK 17+

Spring Boot 3 requires at least JDK 17. Use JDK 17 or newer together with EasyExcel 4.x.

10.3 Response Header for Chinese Filenames

Encode Chinese filenames with

URLEncoder.encode(..., StandardCharsets.UTF_8).replaceAll("\\+", "%20")

to avoid garbled names.

10.4 Memory Management for Large Files

Although EasyExcel is memory‑efficient, storing all rows in a List can still exhaust memory. Process data in batches, persisting each batch to the database and clearing the list.

10.5 Header‑Entity Matching

Excel column headers must exactly match the strings in @ExcelProperty. Mismatched headers result in missing values.

10.6 Date and Number Formatting

Treat phone numbers and ID numbers as strings.

Standardize date formats.

Fix numeric cells that turn into scientific notation.

11. Production‑Grade Enhancements

Validate import parameters (null, empty file).

Check file size and allowed extensions (.xls, .xlsx).

Handle exceptions gracefully.

Batch insert into the database.

Provide import failure feedback.

Offer a template download endpoint.

12. Summary

Integrating EasyExcel into Spring Boot 3 is straightforward. The core steps are:

Add the EasyExcel dependency.

Define a POJO with @ExcelProperty annotations.

Use EasyExcel.write() for export.

Use EasyExcel.read() with a listener for import.

Key points to remember:

Use Jakarta servlet classes.

Encode Chinese filenames.

Avoid loading the entire file into memory for large imports.

Ensure Excel headers match the annotated field names.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmenteasyexcelExcel Importexcel-exportspring-boot-3
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.