Creating a Generic Excel Export Utility with EasyExcel

Overview

For Excel file manipulation in Java applications, Apache POI has been the stendard choice. However, Alibaba's EasyExcel library provides a more streamlined approach with simplified APIs and better performence optimization, particularly when handling large datasets.

Dependency Configuration

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

Generic Export Utility Implementation

package com.example.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class ExportHelper<T> {

    public static <T> void generateExcel(HttpServletResponse response, 
                                       List<T> dataList, 
                                       Class<?> headerClass) throws IOException {
        
        ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();
        WriteSheet worksheet = EasyExcel.writerSheet(0, "Data Sheet")
                                      .head(headerClass)
                                      .build();
        
        writer.write(dataList, worksheet);
        writer.finish();
    }
}

Controller Entegration

@GetMapping("/download-report")
public void downloadReport(HttpServletResponse response) {
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String filename = "station-report-" + System.currentTimeMillis();
        response.setHeader("Content-Disposition", 
                          "attachment; filename=" + filename + ".xlsx");

        List<StationData> sourceData = dataService.getAllStations();
        List<StationExportDTO> exportData = sourceData.stream()
            .map(source -> {
                StationExportDTO target = new StationExportDTO();
                BeanUtils.copyProperties(source, target);
                return target;
            })
            .collect(Collectors.toList());

        ExportHelper.generateExcel(response, exportData, StationExportDTO.class);

    } catch (IOException ex) {
        throw new ServiceException("Failed to generate export file", ex);
    }
}

Data Model Configuration

@Data
@HeadRowHeight(45)
public class StationExportDTO {
    
    @ExcelProperty(value = "Station Address Code", index = 0)
    @ColumnWidth(25)
    private String addressIdentifier;

    @ExcelProperty(value = "Location Details", index = 1)
    @ColumnWidth(30)
    private String locationInfo;
    
    @ExcelProperty(value = "Installation Date", index = 2)
    @ColumnWidth(20)
    private String installationDate;
}

Tags: EasyExcel java Spring Boot Excel Export Apache POI

Posted on Sat, 12 Sep 2026 16:14:05 +0000 by my8by10