[测评系统]--测评系统核心代码库
林致杰
2022-07-25 a4d957be987b9e0240323499e0440b773bf2a5f3
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
package com.ots.common.utils.poi;
import com.ots.common.exception.BusinessException;
import com.ots.common.utils.DateUtils;
import com.ots.common.utils.StringUtils;
import com.ots.common.utils.reflect.ReflectUtils;
import com.ots.common.utils.text.Convert;
import com.ots.framework.aspectj.lang.annotation.Excel;
import com.ots.framework.aspectj.lang.annotation.Excel.ColumnType;
import com.ots.framework.aspectj.lang.annotation.Excel.Type;
import com.ots.framework.aspectj.lang.annotation.Excels;
import com.ots.framework.config.EssConfig;
import com.ots.framework.web.domain.AjaxResult;
import com.ots.project.exam.domain.TQuestion;
import com.ots.project.exam.dto.DataMap;
import com.ots.project.exam.dto.QuestionEditItem;
import com.ots.project.exam.dto.QuestionItem;
import com.ots.project.exam.dto.QuestionJobImport;
import com.ots.project.exam.dto.QuestionPersonalityImport;
import com.ots.project.tool.exam.JsonUtil;
import com.ots.project.tool.exam.ZipUtil;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
 
public class ExcelUtil<T> {
    
    public static final int sheetSize = 65536;
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
    
    public Class<T> clazz;
    
    private String sheetName;
    
    private Type type;
    
    private Workbook wb;
    
    private Sheet sheet;
    
    private Map<String, CellStyle> styles;
    
    private List<T> list;
    
    private List<Object[]> fields;
    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }
    
    public static String convertByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource) {
                String[] itemArray = item.split("=");
                if (itemArray[0].equals(propertyValue)) {
                    return itemArray[1];
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return propertyValue;
    }
    
    public static String reverseByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource) {
                String[] itemArray = item.split("=");
                if (itemArray[1].equals(propertyValue)) {
                    return itemArray[0];
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return propertyValue;
    }
    public void init(List<T> list, String sheetName, Type type) {
        if (list == null) {
            list = new ArrayList<T>();
        }
        this.list = list;
        this.sheetName = sheetName;
        this.type = type;
        createExcelField();
        createWorkbook();
    }
    
    public List<T> importExcel(InputStream input) throws Exception {
        return importExcel(StringUtils.EMPTY, input);
    }
    
    public List<T> importExcel(String sheetName, InputStream input) throws Exception {
        this.type = Type.IMPORT;
        this.wb = WorkbookFactory.create(input);
        List<T> list = new ArrayList<T>();
        Sheet sheet = null;
        if (StringUtils.isNotEmpty(sheetName)) {
            
            sheet = wb.getSheet(sheetName);
        } else {
            
            sheet = wb.getSheetAt(0);
        }
        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }
        int rows = sheet.getPhysicalNumberOfRows();
        if (rows > 0) {
            
            Map<String, Integer> cellMap = new HashMap<String, Integer>();
            
            Row heard = sheet.getRow(0);
            for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                Cell cell = heard.getCell(i);
                if (StringUtils.isNotNull(cell != null)) {
                    String value = this.getCellValue(heard, i).toString();
                    cellMap.put(value, i);
                } else {
                    cellMap.put(null, i);
                }
            }
            
            Field[] allFields = clazz.getDeclaredFields();
            
            Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
            for (int col = 0; col < allFields.length; col++) {
                Field field = allFields[col];
                Excel attr = field.getAnnotation(Excel.class);
                if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
                    
                    field.setAccessible(true);
                    Integer column = cellMap.get(attr.name());
                    fieldsMap.put(column, field);
                }
            }
            for (int i = 1; i < rows; i++) {
                
                Row row = sheet.getRow(i);
                T entity = null;
                for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
                    Object val = this.getCellValue(row, entry.getKey());
                    
                    entity = (entity == null ? clazz.newInstance() : entity);
                    
                    Field field = fieldsMap.get(entry.getKey());
                    
                    Class<?> fieldType = field.getType();
                    if (String.class == fieldType) {
                        String s = Convert.toStr(val);
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = Convert.toStr(val);
                        }
                    } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
                        val = Convert.toInt(val);
                    } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
                        val = Convert.toLong(val);
                    } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
                        val = Convert.toDouble(val);
                    } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
                        val = Convert.toFloat(val);
                    } else if (BigDecimal.class == fieldType) {
                        val = Convert.toBigDecimal(val);
                    } else if (Date.class == fieldType) {
                        if (val instanceof String) {
                            val = DateUtils.parseDate(val);
                        } else if (val instanceof Double) {
                            val = DateUtil.getJavaDate((Double) val);
                        }
                    }
                    if (StringUtils.isNotNull(fieldType)) {
                        Excel attr = field.getAnnotation(Excel.class);
                        String propertyName = field.getName();
                        if (StringUtils.isNotEmpty(attr.targetAttr())) {
                            propertyName = field.getName() + "." + attr.targetAttr();
                        } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
                            val = reverseByExp(String.valueOf(val), attr.readConverterExp());
                        }
                        ReflectUtils.invokeSetter(entity, propertyName, val);
                    }
                }
                list.add(entity);
            }
        }
        return list;
    }
    
    public AjaxResult exportExcel(List<T> list, String sheetName) {
        this.init(list, sheetName, Type.EXPORT);
        return exportExcel();
    }
    
    public AjaxResult importTemplateExcel(String sheetName) {
        this.init(null, sheetName, Type.IMPORT);
        return exportExcel();
    }
    public InputStream importReportInterrelatedExcel(String fileName) {
        InputStream in = null;
        try {
            File file = new File(EssConfig.getReportTemplates() + fileName);
            log.info("loading file = {}",file.getPath());
            in = new FileInputStream(file);
 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return in;
    }
    
    public AjaxResult importTemplateQuestionExcel(String fileName) {
        this.init(null, sheetName, Type.IMPORT);
        String returnMessage = "导出模板转移错误:";
        InputStream in = null;
        OutputStream out = null;
        try {
            in = ExcelUtil.class.getClassLoader().getResourceAsStream("static/downloadTemplates/" + fileName);
            
            String profile = EssConfig.getProfile();
            File fileout = new File(profile + "/download" + fileName);
            if (!fileout.getParentFile().exists()) {
                fileout.getParentFile().mkdirs();
            }
            out = new FileOutputStream(fileout);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            return AjaxResult.success(fileName);
        } catch (Exception ex) {
            returnMessage = returnMessage + ex.getMessage();
            log.error("导出模板转移错误:{}", returnMessage, ex);
        } finally {
            closeChannel(out);
            closeChannel(in);
        }
        return AjaxResult.error(returnMessage);
    }
    private void closeChannel(InputStream inputStream) {
        try {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        } catch (IOException ioe) {
            log.error("关闭通道失败:{}", ioe.getMessage(), ioe);
        }
    }
    private void closeChannel(OutputStream outputStream) {
        try {
            if (Objects.nonNull(outputStream)) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            log.error("关闭通道失败:{}", ioe.getMessage(), ioe);
        }
    }
    
    public AjaxResult exportExcel() {
        OutputStream out = null;
        try {
            
            double sheetNo = Math.ceil(list.size() / sheetSize);
            for (int index = 0; index <= sheetNo; index++) {
                createSheet(sheetNo, index);
                
                Row row = sheet.createRow(0);
                int column = 0;
                
                for (Object[] os : fields) {
                    Excel excel = (Excel) os[1];
                    this.createCell(excel, row, column++);
                }
                if (Type.EXPORT.equals(type)) {
                    fillExcelData(index, row);
                }
            }
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new BusinessException("导出Excel失败,请联系网站管理员!");
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    
    public void fillExcelData(int index, Row row) {
        int startNo = index * sheetSize;
        int endNo = Math.min(startNo + sheetSize, list.size());
        for (int i = startNo; i < endNo; i++) {
            row = sheet.createRow(i + 1 - startNo);
            
            T vo = (T) list.get(i);
            int column = 0;
            for (Object[] os : fields) {
                Field field = (Field) os[0];
                Excel excel = (Excel) os[1];
                
                field.setAccessible(true);
                this.addCell(excel, row, vo, field, column++);
            }
        }
    }
    
    private Map<String, CellStyle> createStyles(Workbook wb) {
        
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);
        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);
        return styles;
    }
    
    public Cell createCell(Excel attr, Row row, int column) {
        
        Cell cell = row.createCell(column);
        
        cell.setCellValue(attr.name());
        setDataValidation(attr, row, column);
        cell.setCellStyle(styles.get("header"));
        return cell;
    }
    
    public void setCellVo(Object value, Excel attr, Cell cell) {
        if (ColumnType.STRING == attr.cellType()) {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(StringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix());
        } else if (ColumnType.NUMERIC == attr.cellType()) {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(Integer.parseInt(value + ""));
        }
    }
    
    public void setDataValidation(Excel attr, Row row, int column) {
        if (attr.name().indexOf("注:") >= 0) {
            sheet.setColumnWidth(column, 6000);
        } else {
            
            sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
            row.setHeight((short) (attr.height() * 20));
        }
        
        if (StringUtils.isNotEmpty(attr.prompt())) {
            
            setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
        }
        
        if (attr.combo().length > 0) {
            
            setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
        }
    }
    
    public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
        Cell cell = null;
        try {
            
            row.setHeight((short) (attr.height() * 20));
            
            if (attr.isExport()) {
                
                cell = row.createCell(column);
                cell.setCellStyle(styles.get("data"));
                
                Object value = getTargetValue(vo, field, attr);
                String dateFormat = attr.dateFormat();
                String readConverterExp = attr.readConverterExp();
                if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) {
                    cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
                } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) {
                    cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
                } else {
                    
                    setCellVo(value, attr, cell);
                }
            }
        } catch (Exception e) {
            log.error("导出Excel失败{}", e);
        }
        return cell;
    }
    
    public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
                              int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        dataValidation.createPromptBox(promptTitle, promptContent);
        dataValidation.setShowPromptBox(true);
        sheet.addValidationData(dataValidation);
    }
    
    public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
        
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        sheet.addValidationData(dataValidation);
    }
    
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }
    
    public String getAbsoluteFile(String filename) {
        String downloadPath = EssConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
    
    public File getAbsoluteFileByName(String filename) {
        String downloadPath = EssConfig.getDownloadPath() + "/" + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return desc;
    }
    public File getAbsoluteFileZipByName(String filename) {
        String downloadPath = EssConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return desc;
    }
    
    private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
        Object o = field.get(vo);
        if (StringUtils.isNotEmpty(excel.targetAttr())) {
            String target = excel.targetAttr();
            if (target.indexOf(".") > -1) {
                String[] targets = target.split("[.]");
                for (String name : targets) {
                    o = getValue(o, name);
                }
            } else {
                o = getValue(o, target);
            }
        }
        return o;
    }
    
    private Object getValue(Object o, String name) throws Exception {
        if (StringUtils.isNotEmpty(name)) {
            Class<?> clazz = o.getClass();
            String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = clazz.getMethod(methodName);
            o = method.invoke(o);
        }
        return o;
    }
    
    private void createExcelField() {
        this.fields = new ArrayList<Object[]>();
        List<Field> tempFields = new ArrayList<>();
        tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
        tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        for (Field field : tempFields) {
            
            if (field.isAnnotationPresent(Excel.class)) {
                putToField(field, field.getAnnotation(Excel.class));
            }
            
            if (field.isAnnotationPresent(Excels.class)) {
                Excels attrs = field.getAnnotation(Excels.class);
                Excel[] excels = attrs.value();
                for (Excel excel : excels) {
                    putToField(field, excel);
                }
            }
        }
    }
    
    private void putToField(Field field, Excel attr) {
        if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
            this.fields.add(new Object[]{field, attr});
        }
    }
    
    public void createWorkbook() {
        this.wb = new SXSSFWorkbook(500);
    }
    
    public void createSheet(double sheetNo, int index) {
        this.sheet = wb.createSheet();
        this.styles = createStyles(wb);
        
        if (sheetNo == 0) {
            wb.setSheetName(index, sheetName);
        } else {
            wb.setSheetName(index, sheetName + index);
        }
    }
    
    public Object getCellValue(Row row, int column) {
        if (row == null) {
            return row;
        }
        Object val = "";
        try {
            Cell cell = row.getCell(column);
            if (cell != null) {
                if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) {
                    val = cell.getNumericCellValue();
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        val = DateUtil.getJavaDate((Double) val); 
                    } else {
                        if ((Double) val % 1 > 0) {
                            val = new DecimalFormat("0.00").format(val);
                        } else {
                            val = new DecimalFormat("0").format(val);
                        }
                    }
                } else if (cell.getCellTypeEnum() == CellType.STRING) {
                    val = cell.getStringCellValue();
                } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
                    val = cell.getBooleanCellValue();
                } else if (cell.getCellTypeEnum() == CellType.ERROR) {
                    val = cell.getErrorCellValue();
                }
            }
        } catch (Exception e) {
            return val;
        }
        return val;
    }
    
    public AjaxResult exportExcelByDataMap(DataMap<Integer, Object[]> dataMap, String fileName) {
        
        XSSFWorkbook workbook = new XSSFWorkbook();
        
        XSSFSheet sheet = workbook.createSheet(fileName);
        
        Set<Integer> keySet = new HashSet<>(dataMap.getKeys());
        int rowNum = 0;
        for (Integer key : keySet) {
            Row row = sheet.createRow(rowNum);
            Object[] objArr =  dataMap.getValues().get(key);
            int cellNum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellNum);
                if (obj instanceof String) {
                    cell.setCellValue((String) obj);
                    if (rowNum == 0) {
                        sheet.autoSizeColumn(cellNum);
                        int length = sheet.getColumnWidth(cellNum) * 17 / 10;
                        sheet.setColumnWidth(cellNum, length < 65270 ? length : 65270);
                    }
                } else if (obj instanceof Integer) {
                    cell.setCellValue((Integer) obj);
                }
                cellNum++;
            }
            rowNum++;
        }
        FileOutputStream out = null;
        FileOutputStream zipOut = null;
        this.sheetName = "report";
        try {
            String fileSuffix = ".xlsx";
            String zipSuffix = ".zip";
            File file = getAbsoluteFileByName(fileName + fileSuffix);
            File fileZip = getAbsoluteFileZipByName(fileName + zipSuffix);
            out = new FileOutputStream(file);
            zipOut = new FileOutputStream(fileZip);
            workbook.write(out);
            List<File> fileList = new ArrayList<>();
            fileList.add(file);
            ZipUtil.toZip(fileList, zipOut);
            file.delete();
            return AjaxResult.success(fileName + zipSuffix);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new BusinessException("导出Excel失败,请联系网站管理员!");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (zipOut != null) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    public List<Map<Integer, String>> importDynamicExcel(InputStream is) throws Exception {
        
        this.type = Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        List<Map<Integer, String>> excelList = new ArrayList<>();
        Sheet sheet = null;
        if (StringUtils.isNotEmpty(sheetName)) {
            
            sheet = wb.getSheet(sheetName);
        } else {
            
            sheet = wb.getSheetAt(0);
        }
        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }
        
        int rows = sheet.getPhysicalNumberOfRows();
        if (rows < 0) {
            return excelList;
        }
        
        Field[] allFields = clazz.getDeclaredFields();
        Map<Integer, String> attrMap = new HashMap<>();
        for (int i = 0; i < allFields.length; i++) {
            Excel attr = allFields[i].getAnnotation(Excel.class);
            if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
                attrMap.put(i, attr.name());
            }
        }
        
        Map<Integer, String> cellHeadMap = new HashMap<Integer, String>();
        Row heard = sheet.getRow(0);
        for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
            Cell cell = heard.getCell(i);
            if (StringUtils.isNotNull(cell != null)) {
                String value = this.getCellValue(heard, i).toString();
                cellHeadMap.put(i, value);
            } else {
                cellHeadMap.put(i, null);
            }
        }
        
        
        for (int i = 0; i < 3; i++) {
            if (!cellHeadMap.get(i).contains(attrMap.get(i))) {
                return excelList;
            }
        }
        
        excelList.add(cellHeadMap);
        QuestionJobImport questionJobImport = (QuestionJobImport) clazz.newInstance();
        
        for (int i = 1; i < rows; i++) {
            
            Row data = sheet.getRow(i);
            Map<Integer, String> cellDataMap = new HashMap<Integer, String>();
            for (int j = 0; j < data.getPhysicalNumberOfCells(); j++) {
                Cell cell = data.getCell(j);
                if (StringUtils.isNotNull(cell != null)) {
                    String value = this.getCellValue(data, j).toString();
                    cellDataMap.put(j, value);
                } else {
                    cellDataMap.put(j, null);
                }
            }
            excelList.add(cellDataMap);
        }
        return excelList;
    }
    
    public QuestionJobImport importJobExcel(InputStream is, Long levelId, String levelName, String langType) throws Exception {
        
        this.type = Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        QuestionJobImport questionJobImport = (QuestionJobImport) clazz.newInstance();
        
        questionJobImport.setLangType(langType);
        
        Sheet questionSheet = wb.getSheetAt(0);
        if (questionSheet == null) {
            throw new IOException("文件sheet不存在");
        }
        
        int questionRows = questionSheet.getPhysicalNumberOfRows();
        if (questionRows < 0) {
            return questionJobImport;
        }
        
        Map<Integer, String> cellHeadMap = new HashMap<Integer, String>();
        Row heard = questionSheet.getRow(0);
        
        int colNum = heard.getPhysicalNumberOfCells();
        
        
        List<String> multilingualList = new ArrayList<>();
        for (int i = 0; i < colNum; i++) {
            Cell cell = heard.getCell(i);
            String value = "";
            if (Objects.nonNull(cell) && StringUtils.isNotEmpty(value = this.getCellValue(heard, i).toString().trim())) {
                cellHeadMap.put(i, value);
                multilingualList.add(value);
            }
        }
        
        if (!StringUtils.equals(cellHeadMap.get(0), "ID")) {
            questionJobImport.setLangType("");
            return questionJobImport;
        }
        
        questionJobImport.setPermanentIdList(new ArrayList<>());
        List<String> permanentIdList = questionJobImport.getPermanentIdList();
        
        questionJobImport.setQuestionStrList(new ArrayList<>());
        List<String> questionStrList = questionJobImport.getQuestionStrList();
        
        questionJobImport.setItemList(new ArrayList<>());
        List<QuestionItem> itemsList = questionJobImport.getItemList();
        
        Set<Integer> colNumSet = new HashSet<>();
        for (int i = 1; i < questionRows; i++) {
            Row data = questionSheet.getRow(i);
            for (int j = 1; j < colNum; j++) {
                Cell questionCell = data.getCell(j);
                if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
                    colNumSet.add(j);
                }
            }
        }
        
        List<String> multilingualResultList = new ArrayList<>();
        if (StringUtils.equals(langType, "ALL")) {
            for (int langNum : colNumSet) {
                multilingualResultList.add(multilingualList.get(langNum));
            }
        } else {
            for (int langNum : colNumSet) {
                if (StringUtils.equals(langType, multilingualList.get(langNum))) {
                    multilingualResultList.add(multilingualList.get(langNum));
                }
            }
        }
        
        if (multilingualResultList.isEmpty()) {
            questionJobImport.setLangType("");
            return questionJobImport;
        }
        questionJobImport.setMultilingualList(multilingualResultList);
        questionJobImport.setQuestionList(new ArrayList<>());
        List<TQuestion> tQuestionList = questionJobImport.getQuestionList();
        
        for (int i = 1; i < questionRows; i++) {
            
            Row data = questionSheet.getRow(i);
            if (this.getCellValue(data, 0).toString().trim().isEmpty()) {
                break;
            }
            
            Cell permanentCell = data.getCell(0);
            if (StringUtils.isNotNull(permanentCell)) {
                permanentIdList.add(this.getCellValue(data, 0).toString().trim());
            }
            
            Map<String, String> questionMap = new HashMap<>();
            for (int j : colNumSet) {
                Cell questionCell = data.getCell(j);
                if (StringUtils.isNotNull(questionCell)) {
                    questionMap.put(cellHeadMap.get(j), this.getCellValue(data, j).toString().trim());
                }
            }
            questionStrList.add(JsonUtil.toJsonStr(questionMap));
            
            TQuestion question = new TQuestion();
            
            question.setPermanentId(permanentIdList.get(i - 1));
            question.setDeleted(1L);
            question.setLangType("English");
            question.setLevelId(levelId);
            question.setLevelName(levelName);
            question.setTitle(JsonUtil.toJsonStr(questionMap));
            tQuestionList.add(question);
        }
        return questionJobImport;
    }
    
    public QuestionPersonalityImport importPersonalityExcel(InputStream is, Long levelId, String levelName, String langType) throws Exception {
        
        this.type = Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        QuestionPersonalityImport questionPersonalityImport = (QuestionPersonalityImport) clazz.newInstance();
        
        questionPersonalityImport.setLangType(langType);
        
        Sheet questionSheet = wb.getSheetAt(0);
        
        Sheet itemSheet = wb.getSheetAt(1);
        
        if (questionSheet == null || itemSheet == null) {
            throw new IOException("file sheet does not exist");
        }
        
        int questionRows = questionSheet.getPhysicalNumberOfRows();
        int itemRows = itemSheet.getPhysicalNumberOfRows();
        if (questionRows < 0 || itemRows < 0) {
            return questionPersonalityImport;
        }
        
        Row questionHead = questionSheet.getRow(0);
        Row itemHead = itemSheet.getRow(0);
        
        int questionHeadColNum = questionHead.getPhysicalNumberOfCells();
        int itemHeadColNum = itemHead.getPhysicalNumberOfCells();
        
        Map<Integer, String> questionHeadMap = new HashMap<>();
        
        Map<Integer, String> itemHeadMap = new HashMap<>();
        
        List<String> multilingualList = new ArrayList<>();
        for (int i = 0; i < questionHeadColNum; i++) {
            Cell cell = questionHead.getCell(i);
            String value = "";
            if (Objects.nonNull(cell) && StringUtils.isNotEmpty(this.getCellValue(questionHead, i).toString().trim())) {
                value = this.getCellValue(questionHead, i).toString().trim();
                questionHeadMap.put(i, value);
                multilingualList.add(value);
            }
        }
        
        if (!StringUtils.equals(questionHeadMap.get(0), "ID")) {
            questionPersonalityImport.setLangType("");
            return questionPersonalityImport;
        }
        for (int i = 0; i < itemHeadColNum; i++) {
            Cell cell = itemHead.getCell(i);
            if (StringUtils.isNotNull(cell != null)) {
                String value = this.getCellValue(itemHead, i).toString();
                itemHeadMap.put(i, value);
            } else {
                itemHeadMap.put(i, "");
            }
        }
        
        
        questionPersonalityImport.setQuestionList(new ArrayList<>());
        List<TQuestion> questionList = questionPersonalityImport.getQuestionList();
        
        
        List<QuestionEditItem> items = new ArrayList<>();
        
        Set<Integer> qustionNumSet = new HashSet<>();
        for (int i = 1; i < questionRows; i++) {
            Row data = questionSheet.getRow(i);
            for (int j = 1; j < questionHeadColNum; j++) {
                Cell questionCell = data.getCell(j);
                if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
                    qustionNumSet.add(j);
                }
            }
        }
        Set<Integer> itemNumSet = new HashSet<>();
        for (int i = 1; i < itemRows; i++) {
            Row data = itemSheet.getRow(i);
            for (int j = 1; j < itemHeadColNum; j++) {
                Cell itemCell = data.getCell(j);
                if (Objects.nonNull(itemCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
                    itemNumSet.add(j);
                }
            }
        }
        
        if (qustionNumSet.size() > itemNumSet.size()) {
            questionPersonalityImport.setLangType("");
            return questionPersonalityImport;
        }
        
        for (int i = 1; i < questionHeadMap.size(); i++) {
            if (!itemHeadMap.containsValue(questionHeadMap.get(i))) {
                questionPersonalityImport.setLangType("");
                return questionPersonalityImport;
            }
        }
        
        List<String> multilingualResultList = new ArrayList<>();
        if (StringUtils.equals(langType, "ALL")) {
            for (int langNum : qustionNumSet) {
                multilingualResultList.add(multilingualList.get(langNum));
            }
        } else {
            for (int langNum : qustionNumSet) {
                if (StringUtils.equals(langType, multilingualList.get(langNum))) {
                    multilingualResultList.add(multilingualList.get(langNum));
                }
            }
        }
        
        if (multilingualResultList.isEmpty()) {
            questionPersonalityImport.setLangType("");
            return questionPersonalityImport;
        }
        questionPersonalityImport.setMultilingualList(multilingualResultList);
        for (int i = 1; i < itemRows; i++) {
            
            Row rowDatas = itemSheet.getRow(i);
            
            if (this.getCellValue(rowDatas, 0).toString().trim().isEmpty()) {
                throw new IOException("No question options");
            }
            
            Cell permanentCell = rowDatas.getCell(0);
            String prefix = "";
            if (StringUtils.isNotNull(permanentCell)) {
                prefix = this.getCellValue(rowDatas, 0).toString().trim();
            }
            
            QuestionEditItem questionEditItem = new QuestionEditItem();
            questionEditItem.setPrefix(prefix); 
            Map<String, String> itemContentMap = new HashMap<>();
            for (int j = 1; j < itemHeadColNum; j++) {
                Cell questionCell = rowDatas.getCell(j);
                if (StringUtils.isNotNull(questionCell)) {
                    itemContentMap.put(itemHeadMap.get(j), this.getCellValue(rowDatas, j).toString().trim());
                }
            }
            questionEditItem.setContent(JsonUtil.toJsonStr(itemContentMap));
            items.add(questionEditItem);
        }
        
        for (int i = 1; i < questionRows; i++) {
            
            Row rowDatas = questionSheet.getRow(i);
            
            if (this.getCellValue(rowDatas, 0).toString().trim().isEmpty()) {
                break;
            }
            
            Cell permanentCell = rowDatas.getCell(0);
            String permanentId = "";
            if (StringUtils.isNotNull(permanentCell)) {
                permanentId = this.getCellValue(rowDatas, 0).toString().trim();
            }
            
            TQuestion question = new TQuestion();
            
            question.setPermanentId(permanentId);
            question.setDeleted(1L);
            question.setLangType("English");
            question.setLevelId(levelId);
            question.setLevelName(levelName);
            
            question.setChoiceInput(new ArrayList<>());
            question.setSelectInput(new ArrayList<>());
            List<String> choiceInput = question.getChoiceInput();
            List<String> selectInput = question.getSelectInput();
            
            items.stream().forEach(questionEditItem -> {
                choiceInput.add(questionEditItem.getPrefix());
                selectInput.add(questionEditItem.getContent());
            });
            Map<String, String> questionTitleMap = new HashMap<>();
            for (int j : qustionNumSet) {
                Cell questionCell = rowDatas.getCell(j);
                if (StringUtils.isNotNull(questionCell)) {
                    
                    questionTitleMap.put(questionHeadMap.get(j), this.getCellValue(rowDatas, j).toString().trim());
                }
            }
            question.setTitle(JsonUtil.toJsonStr(questionTitleMap));
            questionList.add(question);
        }
        return questionPersonalityImport;
    }
    public Map<String, Map<String, String>> getMAQFromExcel() {
        InputStream is = null;
        Map<String, Map<String, String>> mapMap = new HashMap<>();
        try {
            
            is = new FileInputStream(new File(EssConfig.getReportTemplates() + "MAQ掌骏数据试用个人.xlsx"));
            this.type = Type.IMPORT;
            this.wb = WorkbookFactory.create(is);
            
            Sheet sheet = wb.getSheetAt(0);
            Row head = sheet.getRow(0);
            int colNum = head.getPhysicalNumberOfCells();
            int rowsNum = sheet.getPhysicalNumberOfRows();
            
            List<String> headValueList = new ArrayList<>();
            for (int i = 0; i < colNum; i++) {
                Cell cell = head.getCell(i);
                String value = "";
                if (Objects.nonNull(cell) && StringUtils.isNotEmpty(this.getCellValue(head, i).toString().trim())) {
                    value = this.getCellValue(head, i).toString().trim();
                    headValueList.add(value);
                    
                }
            }
            
             for (int i = 1; i < rowsNum; i++) {
 
                Row data = sheet.getRow(i);
                Cell questionCellName = data.getCell(0);
                Map<String, String> valueMap = new HashMap<>();
                if (Objects.nonNull(questionCellName) && StringUtils.isNotEmpty(this.getCellValue(data, 0).toString().trim())) {
                    mapMap.put(this.getCellValue(data, 0).toString().trim(), valueMap);
                } else {
                    continue;
                }
                for (int j = 1; j < colNum; j++) {
                    Cell questionCell = data.getCell(j);
                    if (Objects.nonNull(questionCell) && StringUtils.isNotEmpty(this.getCellValue(data, j).toString().trim())) {
                        
                        String strValue = "";
                        try {
                            strValue = String.valueOf(Math.round(Double.parseDouble(this.getCellValue(data, j).toString().trim())));
                        } catch (Exception e) {
                            strValue = this.getCellValue(data, j).toString().trim();
                        }
 
                        
                        valueMap.put(headValueList.get(j), strValue);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(is)) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mapMap;
    }
}