zhou zhou
15 小时以前 6241b8acad2651564c1c668a9a54821361fbb4af
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package com.vincent.rsf.server.common.utils;
 
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vincent.rsf.framework.common.Cools;
import com.vincent.rsf.framework.common.SpringUtils;
import com.vincent.rsf.server.manager.entity.excel.MatnrsTemplate;
import com.vincent.rsf.server.manager.entity.excel.annotation.ExcelComment;
import com.vincent.rsf.server.system.entity.Fields;
import com.vincent.rsf.server.system.service.FieldsService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
 
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * Created by vincent on 2/17/2024
 */
@Slf4j
public class ExcelUtil {
    private static final Pattern EXTEND_FIELD_SOURCE_PATTERN = Pattern.compile("^extendFields\\.\\[(.+)]$");
    private static final String SEQUENCE_SOURCE = "sequence";
    private static final String SEQUENCE_LABEL = "序号";
 
    public static void build(Workbook workbook, HttpServletResponse response) {
        response.reset();
        Http.cors(response);
        response.setContentType("application/octet-stream; charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("export", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException ignore) {
        }
    }
 
    public static <T> Workbook create(List<T> list, Class<T> clz) {
        return create(list, clz, false);
    }
 
    public static <T> Workbook create(List<T> list, Class<T> clz, boolean flagTemplate) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(clz.getSimpleName());
 
        Row header = sheet.createRow(0);
        Field[] fields = Cools.getAllFields(clz);
        int headerIdx = 0;
        FieldsService itemService = SpringUtils.getBean(FieldsService.class);
        List<Fields> sysFields = itemService.list(new LambdaQueryWrapper<Fields>()
                .eq(Fields::getStatus, 1)
                .eq(Fields::getFlagEnable, 1));
 
 
        for (Field field : fields) {
            if (Modifier.isFinal(field.getModifiers())
                    || Modifier.isStatic(field.getModifiers())
                    || Modifier.isTransient(field.getModifiers())) {
                continue;
            }
            String memo = "Undefined";
            if (flagTemplate) {
                memo = field.getName();
            } else {
                if (field.isAnnotationPresent(Excel.class)) {
                    memo = field.getAnnotation(Excel.class).name();
                }
            }
            if (field.isAnnotationPresent(ApiModelProperty.class)) {
                memo = field.getAnnotation(ApiModelProperty.class).value();
            }
            header.createCell(headerIdx).setCellValue(memo);
            headerIdx++;
        }
        if (clz.equals(MatnrsTemplate.class)) {
            //添加扩展字段别名
            if (!sysFields.isEmpty()) {
                for (Fields field : sysFields) {
                    if (flagTemplate) {
                        header.createCell(headerIdx).setCellValue(field.getFields());
                    } else {
                        header.createCell(headerIdx).setCellValue(field.getFieldsAlise());
                    }
                    headerIdx++;
                }
            }
        }
 
        int rowIndex = 1;
        if (!Objects.isNull(list)) {
            for (T t : list) {
                Row row = sheet.createRow(rowIndex++);
 
                int cellIndex = 0;
                for (Field field : fields) {
                    if (Modifier.isFinal(field.getModifiers())
                            || Modifier.isStatic(field.getModifiers())
                            || Modifier.isTransient(field.getModifiers())) {
                        continue;
                    }
 
                    // 此行很重要,特别是字段为private时
                    field.setAccessible(true);
                    Object value = null;
                    try {
                        value = field.get(t);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    writeCellValue(row, cellIndex, value);
                    cellIndex++;
                }
            }
        }
        for (int i = 0; i <= fields.length; i++) {
            sheet.autoSizeColumn(i);
        }
 
        return workbook;
    }
 
    public static Workbook create(List<Map<String, Object>> rows, List<ExportColumn> columns) {
        return create(rows, columns, null);
    }
 
    public static Workbook create(List<Map<String, Object>> rows, List<ExportColumn> columns, ExportMeta exportMeta) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("export");
        List<ExportColumn> effectiveColumns = buildEffectiveColumns(columns, exportMeta);
        boolean generatedSequenceColumn = hasGeneratedSequenceColumn(columns, effectiveColumns);
        int titleColumnCount = Math.max(effectiveColumns.size(), 4);
        int currentRowIndex = 0;
 
        CellStyle titleStyle = createTitleStyle(workbook);
        CellStyle subHeaderStyle = createSubHeaderStyle(workbook);
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle bodyStyle = createBodyStyle(workbook);
 
        if (exportMeta != null && exportMeta.isLandscape()) {
            sheet.getPrintSetup().setLandscape(true);
        }
 
        if (exportMeta != null && StringUtils.isNotBlank(exportMeta.getReportTitle())) {
            Row titleRow = sheet.createRow(currentRowIndex++);
            titleRow.setHeightInPoints(24);
            Cell titleCell = titleRow.createCell(0);
            titleCell.setCellValue(exportMeta.getReportTitle());
            titleCell.setCellStyle(titleStyle);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titleColumnCount - 1));
 
            Row subHeaderRow = sheet.createRow(currentRowIndex++);
            writeSubHeaderCell(subHeaderRow, 0, getSubHeaderText("报表日期", exportMeta.getReportDate()), subHeaderStyle);
            writeSubHeaderCell(subHeaderRow, 1, getSubHeaderText("打印人", exportMeta.getOperator()), subHeaderStyle);
            writeSubHeaderCell(subHeaderRow, 2, getSubHeaderText("打印时间", exportMeta.getPrintedAt()), subHeaderStyle);
            writeSubHeaderCell(subHeaderRow, 3, getSubHeaderText("记录数", String.valueOf(exportMeta.getCount())), subHeaderStyle);
 
            currentRowIndex++;
        }
 
        Row header = sheet.createRow(currentRowIndex++);
        for (int index = 0; index < effectiveColumns.size(); index++) {
            Cell headerCell = header.createCell(index);
            headerCell.setCellValue(effectiveColumns.get(index).getLabel());
            headerCell.setCellStyle(headerStyle);
        }
 
        int rowIndex = currentRowIndex;
        for (int dataIndex = 0; dataIndex < rows.size(); dataIndex++) {
            Map<String, Object> rowData = rows.get(dataIndex);
            Row row = sheet.createRow(rowIndex++);
            for (int columnIndex = 0; columnIndex < effectiveColumns.size(); columnIndex++) {
                Object value = getExportCellValue(rowData, effectiveColumns.get(columnIndex).getSource(), generatedSequenceColumn, dataIndex);
                writeCellValue(row, columnIndex, value, bodyStyle);
            }
        }
 
        for (int columnIndex = 0; columnIndex < effectiveColumns.size(); columnIndex++) {
            sheet.autoSizeColumn(columnIndex);
        }
 
        return workbook;
    }
 
    private static List<ExportColumn> buildEffectiveColumns(List<ExportColumn> columns, ExportMeta exportMeta) {
        List<ExportColumn> effectiveColumns = new ArrayList<>(columns);
        if (exportMeta != null && exportMeta.isShowSequence() && !containsSequenceColumn(columns)) {
            effectiveColumns.add(0, new ExportColumn(SEQUENCE_SOURCE, SEQUENCE_LABEL));
        }
        return effectiveColumns;
    }
 
    private static boolean containsSequenceColumn(List<ExportColumn> columns) {
        for (ExportColumn column : columns) {
            if (SEQUENCE_SOURCE.equals(column.getSource())) {
                return true;
            }
        }
        return false;
    }
 
    private static boolean hasGeneratedSequenceColumn(List<ExportColumn> originalColumns, List<ExportColumn> effectiveColumns) {
        return effectiveColumns.size() > originalColumns.size()
                && !effectiveColumns.isEmpty()
                && SEQUENCE_SOURCE.equals(effectiveColumns.get(0).getSource());
    }
 
    private static Object getExportCellValue(
            Map<String, Object> rowData,
            String source,
            boolean generatedSequenceColumn,
            int dataIndex
    ) {
        if (generatedSequenceColumn && SEQUENCE_SOURCE.equals(source)) {
            return dataIndex + 1;
        }
        return getRowValue(rowData, source);
    }
 
    private static Object getRowValue(Map<String, Object> rowData, String source) {
        if (rowData == null || StringUtils.isBlank(source)) {
            return null;
        }
 
        if (rowData.containsKey(source)) {
            return rowData.get(source);
        }
 
        Matcher matcher = EXTEND_FIELD_SOURCE_PATTERN.matcher(source);
        if (matcher.matches()) {
            Object extendFields = rowData.get("extendFields");
            if (extendFields instanceof Map<?, ?> extendFieldMap) {
                return extendFieldMap.get(matcher.group(1));
            }
        }
 
        return rowData.get(source);
    }
 
    private static void writeCellValue(Row row, int cellIndex, Object value) {
        writeCellValue(row, cellIndex, value, null);
    }
 
    private static void writeCellValue(Row row, int cellIndex, Object value, CellStyle cellStyle) {
        Cell cell = row.createCell(cellIndex);
        if (cellStyle != null) {
            cell.setCellStyle(cellStyle);
        }
        if (value == null) {
            return;
        }
        if (value instanceof Date) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            cell.setCellValue(sdf.format((Date) value));
            return;
        }
        cell.setCellValue(value.toString());
    }
 
    private static void writeSubHeaderCell(Row row, int cellIndex, String value, CellStyle cellStyle) {
        Cell cell = row.createCell(cellIndex);
        cell.setCellValue(value);
        cell.setCellStyle(cellStyle);
    }
 
    private static String getSubHeaderText(String label, String value) {
        return label + ": " + StringUtils.defaultString(value);
    }
 
    private static CellStyle createTitleStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
 
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 14);
        cellStyle.setFont(font);
        return cellStyle;
    }
 
    private static CellStyle createSubHeaderStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
 
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 10);
        cellStyle.setFont(font);
        return cellStyle;
    }
 
    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
 
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 10);
        cellStyle.setFont(font);
        return cellStyle;
    }
 
    private static CellStyle createBodyStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        cellStyle.setVerticalAlignment(VerticalAlignment.TOP);
        cellStyle.setWrapText(true);
        return cellStyle;
    }
 
    public static class ExportColumn {
        private final String source;
        private final String label;
 
        public ExportColumn(String source, String label) {
            this.source = source;
            this.label = label;
        }
 
        public String getSource() {
            return source;
        }
 
        public String getLabel() {
            return label;
        }
    }
 
    public static class ExportMeta {
        private final String reportTitle;
        private final String reportDate;
        private final String printedAt;
        private final String operator;
        private final int count;
        private final Map<String, Object> reportStyle;
 
        public ExportMeta(String reportTitle, String reportDate, String printedAt, String operator, int count) {
            this(reportTitle, reportDate, printedAt, operator, count, Collections.emptyMap());
        }
 
        public ExportMeta(
                String reportTitle,
                String reportDate,
                String printedAt,
                String operator,
                int count,
                Map<String, ?> reportStyle
        ) {
            this.reportTitle = reportTitle;
            this.reportDate = reportDate;
            this.printedAt = printedAt;
            this.operator = operator;
            this.count = count;
            this.reportStyle = normalizeReportStyle(reportStyle);
        }
 
        public String getReportTitle() {
            return reportTitle;
        }
 
        public String getReportDate() {
            return reportDate;
        }
 
        public String getPrintedAt() {
            return printedAt;
        }
 
        public String getOperator() {
            return operator;
        }
 
        public int getCount() {
            return count;
        }
 
        public Map<String, Object> getReportStyle() {
            return reportStyle;
        }
 
        public boolean isLandscape() {
            return "landscape".equalsIgnoreCase(Objects.toString(getReportStyleValue("orientation"), ""));
        }
 
        public boolean isShowSequence() {
            if (reportStyle.isEmpty() || !reportStyle.containsKey("showSequence")) {
                return true;
            }
            Object value = getReportStyleValue("showSequence");
            if (value instanceof Boolean boolValue) {
                return boolValue;
            }
            return !"false".equalsIgnoreCase(Objects.toString(value, ""));
        }
 
        private Object getReportStyleValue(String key) {
            return reportStyle.get(key);
        }
 
        private static Map<String, Object> normalizeReportStyle(Map<String, ?> reportStyle) {
            if (reportStyle == null || reportStyle.isEmpty()) {
                return Collections.emptyMap();
            }
 
            Map<String, Object> normalizedReportStyle = new HashMap<>();
            for (Map.Entry<String, ?> entry : reportStyle.entrySet()) {
                normalizedReportStyle.put(entry.getKey(), entry.getValue());
            }
            return Collections.unmodifiableMap(normalizedReportStyle);
        }
    }
 
    /**
     * 添加导入excel配置参数
     * 注:默认配置可满足当前需求
     *
     * @return
     */
    public static ImportParams getDefaultImportParams() {
        ImportParams importParams = new ImportParams();
        importParams.setTitleRows(0);
//        importParams.setNeedVerify(true);
        importParams.setHeadRows(1);
        importParams.setSheetNum(1);
        return importParams;
    }
 
    /**
     * 根据 {@code tClass} 相关成员变量的 {@link ExcelComment#example()} 字段创建模拟数据,暂不支持 复杂类型
     *
     * @param tClass
     * @return
     */
    public static <T> T mockData(Class<T> tClass) {
        if (tClass == null) {
            return null;
        }
        T instance = null;
 
        try {
            instance = tClass.newInstance();
            Field[] declaredFields = tClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                ExcelComment comment = declaredField.getAnnotation(ExcelComment.class);
                if (comment == null) {
                    continue;
                }
                declaredField.setAccessible(true);
                Class<?> fieldType = declaredField.getType();
 
                String exampleValue = comment.example();
                Object value = null;
 
                if (fieldType == int.class || fieldType == Integer.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Integer.parseInt(exampleValue);
                } else if (fieldType == short.class || fieldType == Short.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Short.parseShort(exampleValue);
                } else if (fieldType == long.class || fieldType == Long.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Long.parseLong(exampleValue);
                } else if (fieldType == double.class || fieldType == Double.class) {
                    value = StringUtils.isBlank(exampleValue) ? 0 : Double.parseDouble(exampleValue);
                } else if (fieldType == boolean.class || fieldType == Boolean.class) {
                    value = StringUtils.isNotBlank(exampleValue) && Boolean.parseBoolean(exampleValue);
                } else if (fieldType == String.class) {
                    value = exampleValue;
                } else if (fieldType == Date.class) {
                    value = DateUtils.parse(exampleValue);
                }
 
                if (value == null && !isBaseType(fieldType)) {
                    declaredField.set(instance, null);
                } else {
                    declaredField.set(instance, value);
                }
            }
        } catch (Exception e) {
            log.error("数据构造失败,请查询详细信息", e);
            return instance;
        }
 
        return instance;
    }
 
 
    /**
     * 是否是基础数据类型
     *
     * @param className
     * @return
     */
    private static boolean isBaseType(Class<?> className) {
        if (className.equals(java.lang.Integer.class) ||
                className.equals(java.lang.Byte.class) ||
                className.equals(java.lang.Long.class) ||
                className.equals(java.lang.Double.class) ||
                className.equals(java.lang.Float.class) ||
                className.equals(java.lang.Character.class) ||
                className.equals(java.lang.Short.class) ||
                className.equals(java.lang.Boolean.class)) {
            return true;
        }
        return false;
    }
 
 
}