jiangping
2025-03-31 06a46e017886bec692223a626ff50a06b83910cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
package com.doumee.core.annotation.excel;
 
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.core.annotation.AnnotationConfigurationException;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * Excel导出实现
 * @author Eva.Caesar Liu
 * @since 2025/03/31 16:44
 */
@Data
public class ExcelExporter<T> {
 
    private static final String DEFAULT_SHEET_NAME = "Sheet1";
 
    private Class<T> modelClass;
 
    private ExcelExporter(){}
 
    /**
     * 构造器
     *
     * @param modelClass 实体Class对象
     */
    public static <T> ExcelExporter<T> build(Class<T> modelClass) {
        ExcelExporter<T> excelExporter = new ExcelExporter<>();
        excelExporter.setModelClass(modelClass);
        return excelExporter;
    }
 
    /**
     * 导出到指定输出流
     *
     * @param data 数据
     * @param sheetName Sheet名称
     * @param os 输出流
     */
    public void exportData(List<T> data, String sheetName, OutputStream os) {
        SXSSFWorkbook sxssfWorkbook;
        try {
            sxssfWorkbook = new SXSSFWorkbook();
            Sheet sheet = sxssfWorkbook.createSheet(sheetName);
            // 创建列头
            sheet.createFreezePane(0, 1);
            Row header = sheet.createRow(0);
            List<ColumnInfo> columns = this.getColumns();
            for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                ColumnInfo column = columns.get(columnIndex);
                Cell cell = header.createCell(columnIndex);
                cell.setCellValue(column.columnConfig.name());
                // 列宽设置
                if (column.columnConfig.width() == -1) {
                    sheet.setColumnWidth(columnIndex, column.columnConfig.name().length() * 2 * 256);
                } else {
                    sheet.setColumnWidth(columnIndex, column.columnConfig.width() * 2 * 256);
                }
                // 设置列头单元格
                configHeaderCell(sxssfWorkbook, cell, column.columnConfig);
            }
            // 创建数据记录
            for (int rowIndex = 0; rowIndex < data.size(); rowIndex++) {
                Row row = sheet.createRow(rowIndex + 1);
                for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) {
                    ColumnInfo column = columns.get(columnIndex);
                    Cell cell = row.createCell(columnIndex);
                    cell.setCellValue(getCellData(column, data.get(rowIndex)));
                    // 设置数据单元格
                    configDataCell(sxssfWorkbook, cell, column.columnConfig);
                }
            }
            sxssfWorkbook.write(os);
            os.close();
        } catch (Exception e) {
            throw new BusinessException(ResponseStatus.EXPORT_EXCEL_ERROR, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    /**
     * 导出至响应流
     *
     * @param data 数据
     * @param fileName Excel文件名
     * @param sheetName Sheet名称
     * @param response HttpServletResponse对象
     */
    public void exportData(List<T> data, String fileName, String sheetName, HttpServletResponse response) {
        try {
            String encodeFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()) + ".xlsx";
            response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
            response.setContentType("application/octet-stream");
            response.setHeader("eva-opera-type", "download");
            response.setHeader("eva-download-filename", encodeFileName);
            this.exportData(data, sheetName, response.getOutputStream());
        } catch (IOException e) {
            throw new BusinessException(ResponseStatus.EXPORT_EXCEL_ERROR, e);
        }
    }
 
    /**
     * 导出至响应流
     *
     * @param data 数据
     * @param fileName Excel文件名
     * @param response HttpServletResponse对象
     */
    public void exportData(List<T> data, String fileName, HttpServletResponse response) {
        this.exportData(data, fileName, DEFAULT_SHEET_NAME, response);
    }
 
    /**
     * 获取列集合
     */
    private List<ColumnInfo> getColumns () {
        Map<Integer, ColumnInfo> sortedFields = new TreeMap<>();
        Field[] fields = modelClass.getDeclaredFields();
        int index = 0;
        for (Field field : fields) {
            ExcelExportColumn excelColumn = field.getAnnotation(ExcelExportColumn.class);
            if (excelColumn == null) {
                continue;
            }
            if (sortedFields.get(excelColumn.index()) != null) {
                throw new AnnotationConfigurationException("EVA: excel column contains the same index.");
            }
            sortedFields.put(excelColumn.index() == -1 ? index : excelColumn.index(), new ColumnInfo(excelColumn, field));
            index++;
        }
        return new ArrayList<>(sortedFields.values());
    }
 
    /**
     * 配置数据单元格
     */
    private void configDataCell (SXSSFWorkbook workbook, Cell cell, ExcelExportColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置背景
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(columnConfig.dataBackgroundColor().getIndex());
        // 字体
        Font font = workbook.createFont();
        font.setFontHeightInPoints(columnConfig.fontSize());
        // 字体颜色
        font.setColor(columnConfig.color().getIndex());
        // 粗体
        font.setBold(columnConfig.bold());
        // 斜体
        font.setItalic(columnConfig.italic());
        style.setFont(font);
        // 边框
        configCellBorder(style);
        cell.setCellStyle(style);
    }
 
    /**
     * 配置列头单元格
     */
    private void configHeaderCell (SXSSFWorkbook workbook, Cell cell, ExcelExportColumn columnConfig) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(columnConfig.align());
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置背景
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(columnConfig.backgroundColor().getIndex());
        // 字体
        Font font = workbook.createFont();
        font.setFontHeightInPoints(columnConfig.fontSize());
        style.setFont(font);
        // 设置边框
        configCellBorder(style);
        cell.setCellStyle(style);
    }
 
    /**
     * 配置单元格边框
     */
    private void configCellBorder (CellStyle style) {
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    }
 
    /**
     * 处理单元格数据
     */
    private String getCellData (ColumnInfo columnInfo, T row) throws Exception {
        columnInfo.field.setAccessible(Boolean.TRUE);
        Object value = columnInfo.field.get(row);
        columnInfo.field.setAccessible(Boolean.FALSE);
        if (value == null) {
            return "";
        }
        String stringValue = value.toString();
        // 存在自定义数据处理器
        if (!columnInfo.columnConfig.converter().equals(ExcelDataConverterAdapter.class)) {
            try {
                Object instance = columnInfo.columnConfig.converter().newInstance();
                Method convertMethod = columnInfo.columnConfig.converter().getMethod("convert", Object[].class);
                List<Object> args = new ArrayList<>();
                args.add(value);
                for (String arg : columnInfo.columnConfig.args()) {
                    args.add(arg);
                }
                value = convertMethod.invoke(instance, new Object[]{args.toArray()});
                stringValue = value.toString();
            } catch (Exception e) {
                throw new IllegalStateException("EVA: can not convert data by " + columnInfo.columnConfig.converter(), e);
            }
        }
        // 日期处理
        if (!"".equals(columnInfo.columnConfig.dateFormat()) && value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat(columnInfo.columnConfig.dateFormat());
            stringValue = sdf.format((Date) value);
        }
        // 值映射
        if (!"".equals(columnInfo.columnConfig.valueMapping())) {
            String[] segs = columnInfo.columnConfig.valueMapping().split(";");
            for (String seg : segs) {
                String[] mapping = seg.split("=");
                if (value.toString().equals(mapping[0].trim())) {
                    stringValue = mapping[1].trim();
                }
            }
        }
        // 前缀处理
        stringValue = columnInfo.columnConfig.prefix() + stringValue;
        // 后缀处理
        stringValue = stringValue + columnInfo.columnConfig.suffix();
        return stringValue;
    }
 
    /**
     * 列信息
     */
    @Data
    @AllArgsConstructor
    private static class ColumnInfo {
 
        // 列配置
        private ExcelExportColumn columnConfig;
 
        // 字段信息
        private Field field;
    }
 
}