Java Excel Export Utility Class

Refined an earlier utility class for exporting data to Excel format.

Key Features:

  1. Supports header generation directly from class fields
  2. Data list accepts List<custom objects/primitive types/String>
  3. Utility uses varargs for flexible input handling
  4. Non-custom objects support nested lists like List<List<String>>, future enhancements planned for custom object support
  5. Allows specifying export fields and excludes serialVersionUID during serialization

Implementation:

Utility Class:

package com.sk.financial.dg.supervision.util;

import cn.hutool.core.collection.CollUtil;
import com.sk.financial.dg.supervision.config.annotation.ExportDesc;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

public class DgExcelUtil {

    /**
     * Generates an Excel file in xlsx format
     *
     * @param sheetName   Name of the worksheet
     * @param titleClass  Class defining headers
     * @param exportList  Fields to export, empty means all
     * @param data        Data rows, supports custom classes, primitives, and Strings
     * @return XSSFWorkbook instance
     */
    public static XSSFWorkbook getXlsx(String sheetName,
                                       Class> titleClass, List<string> exportList, List>... data) throws IllegalAccessException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(sheetName);
        XSSFRow headerRow = sheet.createRow(0);

        List<string> headers = DgExcelUtil.getTitleListByClass(titleClass, exportList);
        for (int i = 0; i < headers.size(); i++) {
            headerRow.createCell(i).setCellValue(headers.get(i));
        }

        int currentRow = 1;
        for (List> dataList : data) {
            if (CollUtil.isEmpty(dataList)) {
                continue;
            }
            currentRow = DgExcelUtil.setData(sheet, exportList, dataList, currentRow);
        }
        return workbook;
    }

    private static int setData(XSSFSheet sheet, List<string> exportList, List> dataList, int startRow) throws IllegalAccessException {
        if (dataList.get(0).getClass().equals(List.class)
                || dataList.get(0).getClass().toString().contains(Arrays.class.toString())
                || dataList.get(0).getClass().toString().contains(Collections.class.toString())){
            for (Object sublist : dataList) {
                if (CollUtil.isEmpty((List>) sublist)) {
                    continue;
                }
                startRow = DgExcelUtil.setData(sheet, exportList, (List>) sublist, startRow);
            }
            return startRow;
        }
        if (DgExcelUtil.isBaseType(dataList.get(0))) {
            XSSFRow row = sheet.createRow(startRow++);
            for (int j = 0, size = dataList.size(); j < size; j++) {
                Object value = dataList.get(j);
                if (value == null) {
                    continue;
                }
                row.createCell(j).setCellValue(String.valueOf(value));
            }
        }
        else {
            for (Object item : dataList) {
                XSSFRow row = sheet.createRow(startRow++);
                Class> itemClass = item.getClass();
                Field[] fields = itemClass.getDeclaredFields();
                int index = 0;
                for (Field field : fields) {
                    if ("serialVersionUID".equals(field.getName())) {
                        continue;
                    }
                    if (CollUtil.isNotEmpty(exportList) && !exportList.contains(field.getName())) {
                        continue;
                    }
                    field.setAccessible(true);
                    Object fieldValue = field.get(item);
                    if (fieldValue == null) {
                        row.createCell(index).setCellValue("");
                    } else if (fieldValue instanceof Date) {
                        row.createCell(index).setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fieldValue));
                    } else {
                        row.createCell(index).setCellValue(String.valueOf(fieldValue));
                    }
                    index++;
                }
            }
        }
        return startRow;
    }

    public static <t> List<string> getTitleListByClass(Class<t> titleClass, List<string> exportList) {
        List<string> headers = new ArrayList<>();
        Field[] fields = titleClass.getDeclaredFields();
        for (Field field : fields) {
            if (CollUtil.isNotEmpty(exportList) && !exportList.contains(field.getName())) {
                continue;
            }
            ExportDesc annotation = AnnotationUtils.findAnnotation(field, ExportDesc.class);
            if (annotation != null) {
                headers.add(annotation.value());
            }
        }
        return headers;
    }

    public static <t> List<t> castList(Object obj, Class<t> clazz) {
        List<t> result = new ArrayList<>();
        if (obj instanceof List>) {
            for (Object item : (List>) obj) {
                result.add(clazz.cast(item));
            }
            return result;
        }
        return null;
    }

    public static boolean isBaseType(Object object) {
        Class> type = object.getClass();
        return (type.equals(Integer.class) ||
                type.equals(Byte.class) ||
                type.equals(Long.class) ||
                type.equals(Double.class) ||
                type.equals(Float.class) ||
                type.equals(Character.class) ||
                type.equals(Short.class) ||
                type.equals(Boolean.class) ||
                type.equals(String.class));
    }
}
</t></t></t></t></string></string></t></string></t></string></string></string>

API Endpoint:

http://localhost:8080/excel/getExcel

Tags: java Excel poi utility-class reflection

Posted on Wed, 20 May 2026 20:08:46 +0000 by info@ipfaces.org