Encapsulating EasyExcel for Simplified Import/Export in Spring Boot Applications
This article demonstrates how to wrap the EasyExcel library in a Spring Boot + MyBatis‑Plus project, providing a unified component that simplifies Excel import and export through concise annotations, reusable service methods, and customizable converters while addressing common pitfalls such as date handling and template support.
To avoid repetitive and inconsistent Excel handling across multiple project teams, the author creates a unified component that encapsulates EasyExcel, making calls simple and standardized.
Environment preparation
Development stack: Spring Boot, MyBatis‑Plus, and a MySQL database. The article includes the DDL for a sample test table with fields num , sex , name , and born_date .
Usage steps
Inject ExcelService into the controller.
Annotate entity fields with EasyExcel annotations ( @ExcelProperty ) and Swagger @Schema for documentation.
Implement import and export endpoints using excelService.importExcel and excelService.exportExcel .
Full controller code is provided, showing @PostMapping("/importExcel") and @PostMapping("/exportExcel") methods that delegate to the service.
Encapsulation process
Core idea: provide minimal‑dependency interfaces for import and export.
The ExcelService interface defines overloaded methods for exporting (default, with type conversion, with template) and importing (with optional conversion and consumer handling). The implementation DefaultExcelServiceImpl uses EasyExcel to write streams, set response headers, and handle converters such as LocalDateTimeConverter .
Utility class ExcelUtils offers static methods for writing Excel files, exporting with templates, excluding columns, and reading data via listeners. It also includes error handling that resets the HTTP response on failure.
The listener ExcelListener extends AnalysisEventListener , collects parsed rows into a list, logs each row, and provides the collected data to the caller.
Encountered issues and solutions
Date format mismatch when exporting via template – solved by creating a custom DateConverter that handles blank strings and delegates to the default conversion.
Version compatibility – ensure POI and ooxml versions match to avoid runtime errors.
LocalDateTime conversion – a dedicated LocalDateTimeConverter converts between LocalDateTime and formatted strings for both import and export.
Legacy problem
The current EasyExcel version (3.3.2) only supports .xls when exporting with a template; .xlsx is not yet supported.
References include the official EasyExcel documentation and a link to the original Juejin post.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.