admin
3 天以前 768498719683f85e5ed19c73eb3d14cdbf420df4
提交 | 用户 | 时间
e57a89 1 package com.jcdm.common.utils.poi;
2
3 import java.io.File;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.OutputStream;
8 import java.lang.reflect.Field;
9 import java.lang.reflect.Method;
10 import java.lang.reflect.ParameterizedType;
11 import java.math.BigDecimal;
12 import java.text.DecimalFormat;
13 import java.time.LocalDate;
14 import java.time.LocalDateTime;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Collection;
18 import java.util.Comparator;
19 import java.util.Date;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Set;
24 import java.util.UUID;
25 import java.util.stream.Collectors;
26 import javax.servlet.http.HttpServletResponse;
27 import org.apache.commons.lang3.ArrayUtils;
28 import org.apache.commons.lang3.RegExUtils;
29 import org.apache.commons.lang3.reflect.FieldUtils;
30 import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
31 import org.apache.poi.hssf.usermodel.HSSFPicture;
32 import org.apache.poi.hssf.usermodel.HSSFPictureData;
33 import org.apache.poi.hssf.usermodel.HSSFShape;
34 import org.apache.poi.hssf.usermodel.HSSFSheet;
35 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
36 import org.apache.poi.ooxml.POIXMLDocumentPart;
37 import org.apache.poi.ss.usermodel.BorderStyle;
38 import org.apache.poi.ss.usermodel.Cell;
39 import org.apache.poi.ss.usermodel.CellStyle;
40 import org.apache.poi.ss.usermodel.CellType;
41 import org.apache.poi.ss.usermodel.ClientAnchor;
42 import org.apache.poi.ss.usermodel.DataValidation;
43 import org.apache.poi.ss.usermodel.DataValidationConstraint;
44 import org.apache.poi.ss.usermodel.DataValidationHelper;
45 import org.apache.poi.ss.usermodel.DateUtil;
46 import org.apache.poi.ss.usermodel.Drawing;
47 import org.apache.poi.ss.usermodel.FillPatternType;
48 import org.apache.poi.ss.usermodel.Font;
49 import org.apache.poi.ss.usermodel.HorizontalAlignment;
50 import org.apache.poi.ss.usermodel.IndexedColors;
51 import org.apache.poi.ss.usermodel.Name;
52 import org.apache.poi.ss.usermodel.PictureData;
53 import org.apache.poi.ss.usermodel.Row;
54 import org.apache.poi.ss.usermodel.Sheet;
55 import org.apache.poi.ss.usermodel.VerticalAlignment;
56 import org.apache.poi.ss.usermodel.Workbook;
57 import org.apache.poi.ss.usermodel.WorkbookFactory;
58 import org.apache.poi.ss.util.CellRangeAddress;
59 import org.apache.poi.ss.util.CellRangeAddressList;
60 import org.apache.poi.util.IOUtils;
61 import org.apache.poi.xssf.streaming.SXSSFWorkbook;
62 import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
63 import org.apache.poi.xssf.usermodel.XSSFDataValidation;
64 import org.apache.poi.xssf.usermodel.XSSFDrawing;
65 import org.apache.poi.xssf.usermodel.XSSFPicture;
66 import org.apache.poi.xssf.usermodel.XSSFShape;
67 import org.apache.poi.xssf.usermodel.XSSFSheet;
68 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
69 import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import com.jcdm.common.annotation.Excel;
73 import com.jcdm.common.annotation.Excel.ColumnType;
74 import com.jcdm.common.annotation.Excel.Type;
75 import com.jcdm.common.annotation.Excels;
76 import com.jcdm.common.config.MesConfig;
77 import com.jcdm.common.core.domain.AjaxResult;
78 import com.jcdm.common.core.text.Convert;
79 import com.jcdm.common.exception.UtilException;
80 import com.jcdm.common.utils.DateUtils;
81 import com.jcdm.common.utils.DictUtils;
82 import com.jcdm.common.utils.StringUtils;
83 import com.jcdm.common.utils.file.FileTypeUtils;
84 import com.jcdm.common.utils.file.FileUtils;
85 import com.jcdm.common.utils.file.ImageUtils;
86 import com.jcdm.common.utils.reflect.ReflectUtils;
87
88 /**
89  * Excel相关处理
90  * 
91  * @author jc
92  */
93 public class ExcelUtil<T>
94 {
95     private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);
96
97     public static final String FORMULA_REGEX_STR = "=|-|\\+|@";
98
99     public static final String[] FORMULA_STR = { "=", "-", "+", "@" };
100
101     /**
102      * 用于dictType属性数据存储,避免重复查缓存
103      */
104     public Map<String, String> sysDictMap = new HashMap<String, String>();
105
106     /**
107      * Excel sheet最大行数,默认65536
108      */
109     public static final int sheetSize = 65536;
110
111     /**
112      * 工作表名称
113      */
114     private String sheetName;
115
116     /**
117      * 导出类型(EXPORT:导出数据;IMPORT:导入模板)
118      */
119     private Type type;
120
121     /**
122      * 工作薄对象
123      */
124     private Workbook wb;
125
126     /**
127      * 工作表对象
128      */
129     private Sheet sheet;
130
131     /**
132      * 样式列表
133      */
134     private Map<String, CellStyle> styles;
135
136     /**
137      * 导入导出数据列表
138      */
139     private List<T> list;
140
141     /**
142      * 注解列表
143      */
144     private List<Object[]> fields;
145
146     /**
147      * 当前行号
148      */
149     private int rownum;
150
151     /**
152      * 标题
153      */
154     private String title;
155
156     /**
157      * 最大高度
158      */
159     private short maxHeight;
160
161     /**
162      * 合并后最后行数
163      */
164     private int subMergedLastRowNum = 0;
165
166     /**
167      * 合并后开始行数
168      */
169     private int subMergedFirstRowNum = 1;
170
171     /**
172      * 对象的子列表方法
173      */
174     private Method subMethod;
175
176     /**
177      * 对象的子列表属性
178      */
179     private List<Field> subFields;
180
181     /**
182      * 统计列表
183      */
184     private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
185
186     /**
187      * 数字格式
188      */
189     private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
190
191     /**
192      * 实体对象
193      */
194     public Class<T> clazz;
195
196     /**
197      * 需要排除列属性
198      */
199     public String[] excludeFields;
200
201     public ExcelUtil(Class<T> clazz)
202     {
203         this.clazz = clazz;
204     }
205
206     /**
207      * 隐藏Excel中列属性
208      *
209      * @param fields 列属性名 示例[单个"name"/多个"id","name"]
210      * @throws Exception
211      */
212     public void hideColumn(String... fields)
213     {
214         this.excludeFields = fields;
215     }
216
217     public void init(List<T> list, String sheetName, String title, Type type)
218     {
219         if (list == null)
220         {
221             list = new ArrayList<T>();
222         }
223         this.list = list;
224         this.sheetName = sheetName;
225         this.type = type;
226         this.title = title;
227         createExcelField();
228         createWorkbook();
229         createTitle();
230         createSubHead();
231     }
232
233     /**
234      * 创建excel第一行标题
235      */
236     public void createTitle()
237     {
238         if (StringUtils.isNotEmpty(title))
239         {
240             subMergedFirstRowNum++;
241             subMergedLastRowNum++;
242             int titleLastCol = this.fields.size() - 1;
243             if (isSubList())
244             {
245                 titleLastCol = titleLastCol + subFields.size() - 1;
246             }
247             Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
248             titleRow.setHeightInPoints(30);
249             Cell titleCell = titleRow.createCell(0);
250             titleCell.setCellStyle(styles.get("title"));
251             titleCell.setCellValue(title);
252             sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol));
253         }
254     }
255
256     /**
257      * 创建对象的子列表名称
258      */
259     public void createSubHead()
260     {
261         if (isSubList())
262         {
263             subMergedFirstRowNum++;
264             subMergedLastRowNum++;
265             Row subRow = sheet.createRow(rownum);
266             int excelNum = 0;
267             for (Object[] objects : fields)
268             {
269                 Excel attr = (Excel) objects[1];
270                 Cell headCell1 = subRow.createCell(excelNum);
271                 headCell1.setCellValue(attr.name());
272                 headCell1.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
273                 excelNum++;
274             }
275             int headFirstRow = excelNum - 1;
276             int headLastRow = headFirstRow + subFields.size() - 1;
277             if (headLastRow > headFirstRow)
278             {
279                 sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, headFirstRow, headLastRow));
280             }
281             rownum++;
282         }
283     }
284
285     /**
286      * 对excel表单默认第一个索引名转换成list
287      * 
288      * @param is 输入流
289      * @return 转换后集合
290      */
291     public List<T> importExcel(InputStream is)
292     {
293         List<T> list = null;
294         try
295         {
296             list = importExcel(is, 0);
297         }
298         catch (Exception e)
299         {
300             log.error("导入Excel异常{}", e.getMessage());
301             throw new UtilException(e.getMessage());
302         }
303         finally
304         {
305             IOUtils.closeQuietly(is);
306         }
307         return list;
308     }
309
310     /**
311      * 对excel表单默认第一个索引名转换成list
312      * 
313      * @param is 输入流
314      * @param titleNum 标题占用行数
315      * @return 转换后集合
316      */
317     public List<T> importExcel(InputStream is, int titleNum) throws Exception
318     {
319         return importExcel(StringUtils.EMPTY, is, titleNum);
320     }
321
322     /**
323      * 对excel表单指定表格索引名转换成list
324      * 
325      * @param sheetName 表格索引名
326      * @param titleNum 标题占用行数
327      * @param is 输入流
328      * @return 转换后集合
329      */
330     public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception
331     {
332         this.type = Type.IMPORT;
333         this.wb = WorkbookFactory.create(is);
334         List<T> list = new ArrayList<T>();
335         // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
336         Sheet sheet = StringUtils.isNotEmpty(sheetName) ? wb.getSheet(sheetName) : wb.getSheetAt(0);
337         if (sheet == null)
338         {
339             throw new IOException("文件sheet不存在");
340         }
341         boolean isXSSFWorkbook = !(wb instanceof HSSFWorkbook);
342         Map<String, PictureData> pictures;
343         if (isXSSFWorkbook)
344         {
345             pictures = getSheetPictures07((XSSFSheet) sheet, (XSSFWorkbook) wb);
346         }
347         else
348         {
349             pictures = getSheetPictures03((HSSFSheet) sheet, (HSSFWorkbook) wb);
350         }
351         // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1
352         int rows = sheet.getLastRowNum();
353         if (rows > 0)
354         {
355             // 定义一个map用于存放excel列的序号和field.
356             Map<String, Integer> cellMap = new HashMap<String, Integer>();
357             // 获取表头
358             Row heard = sheet.getRow(titleNum);
359             for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++)
360             {
361                 Cell cell = heard.getCell(i);
362                 if (StringUtils.isNotNull(cell))
363                 {
364                     String value = this.getCellValue(heard, i).toString();
365                     cellMap.put(value, i);
366                 }
367                 else
368                 {
369                     cellMap.put(null, i);
370                 }
371             }
372             // 有数据时才处理 得到类的所有field.
373             List<Object[]> fields = this.getFields();
374             Map<Integer, Object[]> fieldsMap = new HashMap<Integer, Object[]>();
375             for (Object[] objects : fields)
376             {
377                 Excel attr = (Excel) objects[1];
378                 Integer column = cellMap.get(attr.name());
379                 if (column != null)
380                 {
381                     fieldsMap.put(column, objects);
382                 }
383             }
384             for (int i = titleNum + 1; i <= rows; i++)
385             {
386                 // 从第2行开始取数据,默认第一行是表头.
387                 Row row = sheet.getRow(i);
388                 // 判断当前行是否是空行
389                 if (isRowEmpty(row))
390                 {
391                     continue;
392                 }
393                 T entity = null;
394                 for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet())
395                 {
396                     Object val = this.getCellValue(row, entry.getKey());
397
398                     // 如果不存在实例则新建.
399                     entity = (entity == null ? clazz.newInstance() : entity);
400                     // 从map中得到对应列的field.
401                     Field field = (Field) entry.getValue()[0];
402                     Excel attr = (Excel) entry.getValue()[1];
403                     // 取得类型,并根据对象类型设置值.
404                     Class<?> fieldType = field.getType();
405                     if (String.class == fieldType)
406                     {
407                         String s = Convert.toStr(val);
408                         if (StringUtils.endsWith(s, ".0"))
409                         {
410                             val = StringUtils.substringBefore(s, ".0");
411                         }
412                         else
413                         {
414                             String dateFormat = field.getAnnotation(Excel.class).dateFormat();
415                             if (StringUtils.isNotEmpty(dateFormat))
416                             {
417                                 val = parseDateToStr(dateFormat, val);
418                             }
419                             else
420                             {
421                                 val = Convert.toStr(val);
422                             }
423                         }
424                     }
425                     else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
426                     {
427                         val = Convert.toInt(val);
428                     }
429                     else if ((Long.TYPE == fieldType || Long.class == fieldType) && StringUtils.isNumeric(Convert.toStr(val)))
430                     {
431                         val = Convert.toLong(val);
432                     }
433                     else if (Double.TYPE == fieldType || Double.class == fieldType)
434                     {
435                         val = Convert.toDouble(val);
436                     }
437                     else if (Float.TYPE == fieldType || Float.class == fieldType)
438                     {
439                         val = Convert.toFloat(val);
440                     }
441                     else if (BigDecimal.class == fieldType)
442                     {
443                         val = Convert.toBigDecimal(val);
444                     }
445                     else if (Date.class == fieldType)
446                     {
447                         if (val instanceof String)
448                         {
449                             val = DateUtils.parseDate(val);
450                         }
451                         else if (val instanceof Double)
452                         {
453                             val = DateUtil.getJavaDate((Double) val);
454                         }
455                     }
456                     else if (Boolean.TYPE == fieldType || Boolean.class == fieldType)
457                     {
458                         val = Convert.toBool(val, false);
459                     }
460                     if (StringUtils.isNotNull(fieldType))
461                     {
462                         String propertyName = field.getName();
463                         if (StringUtils.isNotEmpty(attr.targetAttr()))
464                         {
465                             propertyName = field.getName() + "." + attr.targetAttr();
466                         }
467                         if (StringUtils.isNotEmpty(attr.readConverterExp()))
468                         {
469                             val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
470                         }
471                         else if (StringUtils.isNotEmpty(attr.dictType()))
472                         {
473                             val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator());
474                         }
475                         else if (!attr.handler().equals(ExcelHandlerAdapter.class))
476                         {
477                             val = dataFormatHandlerAdapter(val, attr, null);
478                         }
479                         else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures))
480                         {
481                             PictureData image = pictures.get(row.getRowNum() + "_" + entry.getKey());
482                             if (image == null)
483                             {
484                                 val = "";
485                             }
486                             else
487                             {
488                                 byte[] data = image.getData();
489                                 val = FileUtils.writeImportBytes(data);
490                             }
491                         }
492                         ReflectUtils.invokeSetter(entity, propertyName, val);
493                     }
494                 }
495                 list.add(entity);
496             }
497         }
498         return list;
499     }
500
501     /**
502      * 对list数据源将其里面的数据导入到excel表单
503      * 
504      * @param list 导出数据集合
505      * @param sheetName 工作表的名称
506      * @return 结果
507      */
508     public AjaxResult exportExcel(List<T> list, String sheetName)
509     {
510         return exportExcel(list, sheetName, StringUtils.EMPTY);
511     }
512
513     /**
514      * 对list数据源将其里面的数据导入到excel表单
515      * 
516      * @param list 导出数据集合
517      * @param sheetName 工作表的名称
518      * @param title 标题
519      * @return 结果
520      */
521     public AjaxResult exportExcel(List<T> list, String sheetName, String title)
522     {
523         this.init(list, sheetName, title, Type.EXPORT);
524         return exportExcel();
525     }
526
527     /**
528      * 对list数据源将其里面的数据导入到excel表单
529      * 
530      * @param response 返回数据
531      * @param list 导出数据集合
532      * @param sheetName 工作表的名称
533      * @return 结果
534      */
535     public void exportExcel(HttpServletResponse response, List<T> list, String sheetName)
536     {
537         exportExcel(response, list, sheetName, StringUtils.EMPTY);
538     }
539
540     /**
541      * 对list数据源将其里面的数据导入到excel表单
542      * 
543      * @param response 返回数据
544      * @param list 导出数据集合
545      * @param sheetName 工作表的名称
546      * @param title 标题
547      * @return 结果
548      */
549     public void exportExcel(HttpServletResponse response, List<T> list, String sheetName, String title)
550     {
551         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
552         response.setCharacterEncoding("utf-8");
553         this.init(list, sheetName, title, Type.EXPORT);
554         exportExcel(response);
555     }
556
557     /**
558      * 对list数据源将其里面的数据导入到excel表单
559      * 
560      * @param sheetName 工作表的名称
561      * @return 结果
562      */
563     public AjaxResult importTemplateExcel(String sheetName)
564     {
565         return importTemplateExcel(sheetName, StringUtils.EMPTY);
566     }
567
568     /**
569      * 对list数据源将其里面的数据导入到excel表单
570      * 
571      * @param sheetName 工作表的名称
572      * @param title 标题
573      * @return 结果
574      */
575     public AjaxResult importTemplateExcel(String sheetName, String title)
576     {
577         this.init(null, sheetName, title, Type.IMPORT);
578         return exportExcel();
579     }
580
581     /**
582      * 对list数据源将其里面的数据导入到excel表单
583      * 
584      * @param sheetName 工作表的名称
585      * @return 结果
586      */
587     public void importTemplateExcel(HttpServletResponse response, String sheetName)
588     {
589         importTemplateExcel(response, sheetName, StringUtils.EMPTY);
590     }
591
592     /**
593      * 对list数据源将其里面的数据导入到excel表单
594      * 
595      * @param sheetName 工作表的名称
596      * @param title 标题
597      * @return 结果
598      */
599     public void importTemplateExcel(HttpServletResponse response, String sheetName, String title)
600     {
601         response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
602         response.setCharacterEncoding("utf-8");
603         this.init(null, sheetName, title, Type.IMPORT);
604         exportExcel(response);
605     }
606
607     /**
608      * 对list数据源将其里面的数据导入到excel表单
609      * 
610      * @return 结果
611      */
612     public void exportExcel(HttpServletResponse response)
613     {
614         try
615         {
616             writeSheet();
617             wb.write(response.getOutputStream());
618         }
619         catch (Exception e)
620         {
621             log.error("导出Excel异常{}", e.getMessage());
622         }
623         finally
624         {
625             IOUtils.closeQuietly(wb);
626         }
627     }
628
629     /**
630      * 对list数据源将其里面的数据导入到excel表单
631      * 
632      * @return 结果
633      */
634     public AjaxResult exportExcel()
635     {
636         OutputStream out = null;
637         try
638         {
639             writeSheet();
640             String filename = encodingFilename(sheetName);
641             out = new FileOutputStream(getAbsoluteFile(filename));
642             wb.write(out);
643             return AjaxResult.success(filename);
644         }
645         catch (Exception e)
646         {
647             log.error("导出Excel异常{}", e.getMessage());
648             throw new UtilException("导出Excel失败,请联系网站管理员!");
649         }
650         finally
651         {
652             IOUtils.closeQuietly(wb);
653             IOUtils.closeQuietly(out);
654         }
655     }
656
657     /**
658      * 创建写入数据到Sheet
659      */
660     public void writeSheet()
661     {
662         // 取出一共有多少个sheet.
663         int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
664         for (int index = 0; index < sheetNo; index++)
665         {
666             createSheet(sheetNo, index);
667
668             // 产生一行
669             Row row = sheet.createRow(rownum);
670             int column = 0;
671             // 写入各个字段的列头名称
672             for (Object[] os : fields)
673             {
674                 Field field = (Field) os[0];
675                 Excel excel = (Excel) os[1];
676                 if (Collection.class.isAssignableFrom(field.getType()))
677                 {
678                     for (Field subField : subFields)
679                     {
680                         Excel subExcel = subField.getAnnotation(Excel.class);
681                         this.createHeadCell(subExcel, row, column++);
682                     }
683                 }
684                 else
685                 {
686                     this.createHeadCell(excel, row, column++);
687                 }
688             }
689             if (Type.EXPORT.equals(type))
690             {
691                 fillExcelData(index, row);
692                 addStatisticsRow();
693             }
694         }
695     }
696
697     /**
698      * 填充excel数据
699      * 
700      * @param index 序号
701      * @param row 单元格行
702      */
703     @SuppressWarnings("unchecked")
704     public void fillExcelData(int index, Row row)
705     {
706         int startNo = index * sheetSize;
707         int endNo = Math.min(startNo + sheetSize, list.size());
708         int rowNo = (1 + rownum) - startNo;
709         for (int i = startNo; i < endNo; i++)
710         {
711             rowNo = isSubList() ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rownum - startNo;
712             row = sheet.createRow(rowNo);
713             // 得到导出对象.
714             T vo = (T) list.get(i);
715             Collection<?> subList = null;
716             if (isSubList())
717             {
718                 if (isSubListValue(vo))
719                 {
720                     subList = getListCellValue(vo);
721                     subMergedLastRowNum = subMergedLastRowNum + subList.size();
722                 }
723                 else
724                 {
725                     subMergedFirstRowNum++;
726                     subMergedLastRowNum++;
727                 }
728             }
729             int column = 0;
730             for (Object[] os : fields)
731             {
732                 Field field = (Field) os[0];
733                 Excel excel = (Excel) os[1];
734                 if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList))
735                 {
736                     boolean subFirst = false;
737                     for (Object obj : subList)
738                     {
739                         if (subFirst)
740                         {
741                             rowNo++;
742                             row = sheet.createRow(rowNo);
743                         }
744                         List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
745                         int subIndex = 0;
746                         for (Field subField : subFields)
747                         {
748                             if (subField.isAnnotationPresent(Excel.class))
749                             {
750                                 subField.setAccessible(true);
751                                 Excel attr = subField.getAnnotation(Excel.class);
752                                 this.addCell(attr, row, (T) obj, subField, column + subIndex);
753                             }
754                             subIndex++;
755                         }
756                         subFirst = true;
757                     }
758                     this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
759                 }
760                 else
761                 {
762                     this.addCell(excel, row, vo, field, column++);
763                 }
764             }
765         }
766     }
767
768     /**
769      * 创建表格样式
770      * 
771      * @param wb 工作薄对象
772      * @return 样式列表
773      */
774     private Map<String, CellStyle> createStyles(Workbook wb)
775     {
776         // 写入各条记录,每条记录对应excel表中的一行
777         Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
778         CellStyle style = wb.createCellStyle();
779         style.setAlignment(HorizontalAlignment.CENTER);
780         style.setVerticalAlignment(VerticalAlignment.CENTER);
781         Font titleFont = wb.createFont();
782         titleFont.setFontName("Arial");
783         titleFont.setFontHeightInPoints((short) 16);
784         titleFont.setBold(true);
785         style.setFont(titleFont);
786         styles.put("title", style);
787
788         style = wb.createCellStyle();
789         style.setAlignment(HorizontalAlignment.CENTER);
790         style.setVerticalAlignment(VerticalAlignment.CENTER);
791         style.setBorderRight(BorderStyle.THIN);
792         style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
793         style.setBorderLeft(BorderStyle.THIN);
794         style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
795         style.setBorderTop(BorderStyle.THIN);
796         style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
797         style.setBorderBottom(BorderStyle.THIN);
798         style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
799         Font dataFont = wb.createFont();
800         dataFont.setFontName("Arial");
801         dataFont.setFontHeightInPoints((short) 10);
802         style.setFont(dataFont);
803         styles.put("data", style);
804
805         style = wb.createCellStyle();
806         style.setAlignment(HorizontalAlignment.CENTER);
807         style.setVerticalAlignment(VerticalAlignment.CENTER);
808         Font totalFont = wb.createFont();
809         totalFont.setFontName("Arial");
810         totalFont.setFontHeightInPoints((short) 10);
811         style.setFont(totalFont);
812         styles.put("total", style);
813
814         styles.putAll(annotationHeaderStyles(wb, styles));
815
816         styles.putAll(annotationDataStyles(wb));
817
818         return styles;
819     }
820
821     /**
822      * 根据Excel注解创建表格头样式
823      * 
824      * @param wb 工作薄对象
825      * @return 自定义样式列表
826      */
827     private Map<String, CellStyle> annotationHeaderStyles(Workbook wb, Map<String, CellStyle> styles)
828     {
829         Map<String, CellStyle> headerStyles = new HashMap<String, CellStyle>();
830         for (Object[] os : fields)
831         {
832             Excel excel = (Excel) os[1];
833             String key = StringUtils.format("header_{}_{}", excel.headerColor(), excel.headerBackgroundColor());
834             if (!headerStyles.containsKey(key))
835             {
836                 CellStyle style = wb.createCellStyle();
837                 style.cloneStyleFrom(styles.get("data"));
838                 style.setAlignment(HorizontalAlignment.CENTER);
839                 style.setVerticalAlignment(VerticalAlignment.CENTER);
840                 style.setFillForegroundColor(excel.headerBackgroundColor().index);
841                 style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
842                 Font headerFont = wb.createFont();
843                 headerFont.setFontName("Arial");
844                 headerFont.setFontHeightInPoints((short) 10);
845                 headerFont.setBold(true);
846                 headerFont.setColor(excel.headerColor().index);
847                 style.setFont(headerFont);
848                 headerStyles.put(key, style);
849             }
850         }
851         return headerStyles;
852     }
853
854     /**
855      * 根据Excel注解创建表格列样式
856      * 
857      * @param wb 工作薄对象
858      * @return 自定义样式列表
859      */
860     private Map<String, CellStyle> annotationDataStyles(Workbook wb)
861     {
862         Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
863         for (Object[] os : fields)
864         {
865             Excel excel = (Excel) os[1];
866             String key = StringUtils.format("data_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor());
867             if (!styles.containsKey(key))
868             {
869                 CellStyle style = wb.createCellStyle();
870                 style.setAlignment(excel.align());
871                 style.setVerticalAlignment(VerticalAlignment.CENTER);
872                 style.setBorderRight(BorderStyle.THIN);
873                 style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
874                 style.setBorderLeft(BorderStyle.THIN);
875                 style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
876                 style.setBorderTop(BorderStyle.THIN);
877                 style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
878                 style.setBorderBottom(BorderStyle.THIN);
879                 style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
880                 style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
881                 style.setFillForegroundColor(excel.backgroundColor().getIndex());
882                 Font dataFont = wb.createFont();
883                 dataFont.setFontName("Arial");
884                 dataFont.setFontHeightInPoints((short) 10);
885                 dataFont.setColor(excel.color().index);
886                 style.setFont(dataFont);
887                 styles.put(key, style);
888             }
889         }
890         return styles;
891     }
892
893     /**
894      * 创建单元格
895      */
896     public Cell createHeadCell(Excel attr, Row row, int column)
897     {
898         // 创建列
899         Cell cell = row.createCell(column);
900         // 写入列信息
901         cell.setCellValue(attr.name());
902         setDataValidation(attr, row, column);
903         cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
904         if (isSubList())
905         {
906             // 填充默认样式,防止合并单元格样式失效
907             sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
908             if (attr.needMerge())
909             {
910                 sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column));
911             }
912         }
913         return cell;
914     }
915
916     /**
917      * 设置单元格信息
918      * 
919      * @param value 单元格值
920      * @param attr 注解相关
921      * @param cell 单元格信息
922      */
923     public void setCellVo(Object value, Excel attr, Cell cell)
924     {
925         if (ColumnType.STRING == attr.cellType())
926         {
927             String cellValue = Convert.toStr(value);
928             // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。
929             if (StringUtils.startsWithAny(cellValue, FORMULA_STR))
930             {
931                 cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
932             }
933             if (value instanceof Collection && StringUtils.equals("[]", cellValue))
934             {
935                 cellValue = StringUtils.EMPTY;
936             }
937             cell.setCellValue(StringUtils.isNull(cellValue) ? attr.defaultValue() : cellValue + attr.suffix());
938         }
939         else if (ColumnType.NUMERIC == attr.cellType())
940         {
941             if (StringUtils.isNotNull(value))
942             {
943                 cell.setCellValue(StringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
944             }
945         }
946         else if (ColumnType.IMAGE == attr.cellType())
947         {
948             ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
949             String imagePath = Convert.toStr(value);
950             if (StringUtils.isNotEmpty(imagePath))
951             {
952                 byte[] data = ImageUtils.getImage(imagePath);
953                 getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
954                         cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
955             }
956         }
957     }
958
959     /**
960      * 获取画布
961      */
962     public static Drawing<?> getDrawingPatriarch(Sheet sheet)
963     {
964         if (sheet.getDrawingPatriarch() == null)
965         {
966             sheet.createDrawingPatriarch();
967         }
968         return sheet.getDrawingPatriarch();
969     }
970
971     /**
972      * 获取图片类型,设置图片插入类型
973      */
974     public int getImageType(byte[] value)
975     {
976         String type = FileTypeUtils.getFileExtendName(value);
977         if ("JPG".equalsIgnoreCase(type))
978         {
979             return Workbook.PICTURE_TYPE_JPEG;
980         }
981         else if ("PNG".equalsIgnoreCase(type))
982         {
983             return Workbook.PICTURE_TYPE_PNG;
984         }
985         return Workbook.PICTURE_TYPE_JPEG;
986     }
987
988     /**
989      * 创建表格样式
990      */
991     public void setDataValidation(Excel attr, Row row, int column)
992     {
993         if (attr.name().indexOf("注:") >= 0)
994         {
995             sheet.setColumnWidth(column, 6000);
996         }
997         else
998         {
999             // 设置列宽
1000             sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
1001         }
1002         if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0)
1003         {
1004             if (attr.combo().length > 15 || StringUtils.join(attr.combo()).length() > 255)
1005             {
1006                 // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到
1007                 setXSSFValidationWithHidden(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
1008             }
1009             else
1010             {
1011                 // 提示信息或只能选择不能输入的列内容.
1012                 setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column);
1013             }
1014         }
1015     }
1016
1017     /**
1018      * 添加单元格
1019      */
1020     public Cell addCell(Excel attr, Row row, T vo, Field field, int column)
1021     {
1022         Cell cell = null;
1023         try
1024         {
1025             // 设置行高
1026             row.setHeight(maxHeight);
1027             // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
1028             if (attr.isExport())
1029             {
1030                 // 创建cell
1031                 cell = row.createCell(column);
1032                 if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge())
1033                 {
1034                     CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
1035                     sheet.addMergedRegion(cellAddress);
1036                 }
1037                 cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
1038
1039                 // 用于读取对象中的属性
1040                 Object value = getTargetValue(vo, field, attr);
1041                 String dateFormat = attr.dateFormat();
1042                 String readConverterExp = attr.readConverterExp();
1043                 String separator = attr.separator();
1044                 String dictType = attr.dictType();
1045                 if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value))
1046                 {
1047                     cell.setCellValue(parseDateToStr(dateFormat, value));
1048                 }
1049                 else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value))
1050                 {
1051                     cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator));
1052                 }
1053                 else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value))
1054                 {
1055                     if (!sysDictMap.containsKey(dictType + value))
1056                     {
1057                         String lable = convertDictByExp(Convert.toStr(value), dictType, separator);
1058                         sysDictMap.put(dictType + value, lable);
1059                     }
1060                     cell.setCellValue(sysDictMap.get(dictType + value));
1061                 }
1062                 else if (value instanceof BigDecimal && -1 != attr.scale())
1063                 {
1064                     cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue());
1065                 }
1066                 else if (!attr.handler().equals(ExcelHandlerAdapter.class))
1067                 {
1068                     cell.setCellValue(dataFormatHandlerAdapter(value, attr, cell));
1069                 }
1070                 else
1071                 {
1072                     // 设置列类型
1073                     setCellVo(value, attr, cell);
1074                 }
1075                 addStatisticsData(column, Convert.toStr(value), attr);
1076             }
1077         }
1078         catch (Exception e)
1079         {
1080             log.error("导出Excel失败{}", e);
1081         }
1082         return cell;
1083     }
1084
1085     /**
1086      * 设置 POI XSSFSheet 单元格提示或选择框
1087      * 
1088      * @param sheet 表单
1089      * @param textlist 下拉框显示的内容
1090      * @param promptContent 提示内容
1091      * @param firstRow 开始行
1092      * @param endRow 结束行
1093      * @param firstCol 开始列
1094      * @param endCol 结束列
1095      */
1096     public void setPromptOrValidation(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow,
1097             int firstCol, int endCol)
1098     {
1099         DataValidationHelper helper = sheet.getDataValidationHelper();
1100         DataValidationConstraint constraint = textlist.length > 0 ? helper.createExplicitListConstraint(textlist) : helper.createCustomConstraint("DD1");
1101         CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
1102         DataValidation dataValidation = helper.createValidation(constraint, regions);
1103         if (StringUtils.isNotEmpty(promptContent))
1104         {
1105             // 如果设置了提示信息则鼠标放上去提示
1106             dataValidation.createPromptBox("", promptContent);
1107             dataValidation.setShowPromptBox(true);
1108         }
1109         // 处理Excel兼容性问题
1110         if (dataValidation instanceof XSSFDataValidation)
1111         {
1112             dataValidation.setSuppressDropDownArrow(true);
1113             dataValidation.setShowErrorBox(true);
1114         }
1115         else
1116         {
1117             dataValidation.setSuppressDropDownArrow(false);
1118         }
1119         sheet.addValidationData(dataValidation);
1120     }
1121
1122     /**
1123      * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框).
1124      * 
1125      * @param sheet 要设置的sheet.
1126      * @param textlist 下拉框显示的内容
1127      * @param promptContent 提示内容
1128      * @param firstRow 开始行
1129      * @param endRow 结束行
1130      * @param firstCol 开始列
1131      * @param endCol 结束列
1132      */
1133     public void setXSSFValidationWithHidden(Sheet sheet, String[] textlist, String promptContent, int firstRow, int endRow, int firstCol, int endCol)
1134     {
1135         String hideSheetName = "combo_" + firstCol + "_" + endCol;
1136         Sheet hideSheet = wb.createSheet(hideSheetName); // 用于存储 下拉菜单数据
1137         for (int i = 0; i < textlist.length; i++)
1138         {
1139             hideSheet.createRow(i).createCell(0).setCellValue(textlist[i]);
1140         }
1141         // 创建名称,可被其他单元格引用
1142         Name name = wb.createName();
1143         name.setNameName(hideSheetName + "_data");
1144         name.setRefersToFormula(hideSheetName + "!$A$1:$A$" + textlist.length);
1145         DataValidationHelper helper = sheet.getDataValidationHelper();
1146         // 加载下拉列表内容
1147         DataValidationConstraint constraint = helper.createFormulaListConstraint(hideSheetName + "_data");
1148         // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
1149         CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
1150         // 数据有效性对象
1151         DataValidation dataValidation = helper.createValidation(constraint, regions);
1152         if (StringUtils.isNotEmpty(promptContent))
1153         {
1154             // 如果设置了提示信息则鼠标放上去提示
1155             dataValidation.createPromptBox("", promptContent);
1156             dataValidation.setShowPromptBox(true);
1157         }
1158         // 处理Excel兼容性问题
1159         if (dataValidation instanceof XSSFDataValidation)
1160         {
1161             dataValidation.setSuppressDropDownArrow(true);
1162             dataValidation.setShowErrorBox(true);
1163         }
1164         else
1165         {
1166             dataValidation.setSuppressDropDownArrow(false);
1167         }
1168
1169         sheet.addValidationData(dataValidation);
1170         // 设置hiddenSheet隐藏
1171         wb.setSheetHidden(wb.getSheetIndex(hideSheet), true);
1172     }
1173
1174     /**
1175      * 解析导出值 0=男,1=女,2=未知
1176      * 
1177      * @param propertyValue 参数值
1178      * @param converterExp 翻译注解
1179      * @param separator 分隔符
1180      * @return 解析后值
1181      */
1182     public static String convertByExp(String propertyValue, String converterExp, String separator)
1183     {
1184         StringBuilder propertyString = new StringBuilder();
1185         String[] convertSource = converterExp.split(",");
1186         for (String item : convertSource)
1187         {
1188             String[] itemArray = item.split("=");
1189             if (StringUtils.containsAny(propertyValue, separator))
1190             {
1191                 for (String value : propertyValue.split(separator))
1192                 {
1193                     if (itemArray[0].equals(value))
1194                     {
1195                         propertyString.append(itemArray[1] + separator);
1196                         break;
1197                     }
1198                 }
1199             }
1200             else
1201             {
1202                 if (itemArray[0].equals(propertyValue))
1203                 {
1204                     return itemArray[1];
1205                 }
1206             }
1207         }
1208         return StringUtils.stripEnd(propertyString.toString(), separator);
1209     }
1210
1211     /**
1212      * 反向解析值 男=0,女=1,未知=2
1213      * 
1214      * @param propertyValue 参数值
1215      * @param converterExp 翻译注解
1216      * @param separator 分隔符
1217      * @return 解析后值
1218      */
1219     public static String reverseByExp(String propertyValue, String converterExp, String separator)
1220     {
1221         StringBuilder propertyString = new StringBuilder();
1222         String[] convertSource = converterExp.split(",");
1223         for (String item : convertSource)
1224         {
1225             String[] itemArray = item.split("=");
1226             if (StringUtils.containsAny(propertyValue, separator))
1227             {
1228                 for (String value : propertyValue.split(separator))
1229                 {
1230                     if (itemArray[1].equals(value))
1231                     {
1232                         propertyString.append(itemArray[0] + separator);
1233                         break;
1234                     }
1235                 }
1236             }
1237             else
1238             {
1239                 if (itemArray[1].equals(propertyValue))
1240                 {
1241                     return itemArray[0];
1242                 }
1243             }
1244         }
1245         return StringUtils.stripEnd(propertyString.toString(), separator);
1246     }
1247
1248     /**
1249      * 解析字典值
1250      * 
1251      * @param dictValue 字典值
1252      * @param dictType 字典类型
1253      * @param separator 分隔符
1254      * @return 字典标签
1255      */
1256     public static String convertDictByExp(String dictValue, String dictType, String separator)
1257     {
1258         return DictUtils.getDictLabel(dictType, dictValue, separator);
1259     }
1260
1261     /**
1262      * 反向解析值字典值
1263      * 
1264      * @param dictLabel 字典标签
1265      * @param dictType 字典类型
1266      * @param separator 分隔符
1267      * @return 字典值
1268      */
1269     public static String reverseDictByExp(String dictLabel, String dictType, String separator)
1270     {
1271         return DictUtils.getDictValue(dictType, dictLabel, separator);
1272     }
1273
1274     /**
1275      * 数据处理器
1276      * 
1277      * @param value 数据值
1278      * @param excel 数据注解
1279      * @return
1280      */
1281     public String dataFormatHandlerAdapter(Object value, Excel excel, Cell cell)
1282     {
1283         try
1284         {
1285             Object instance = excel.handler().newInstance();
1286             Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class });
1287             value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb);
1288         }
1289         catch (Exception e)
1290         {
1291             log.error("不能格式化数据 " + excel.handler(), e.getMessage());
1292         }
1293         return Convert.toStr(value);
1294     }
1295
1296     /**
1297      * 合计统计信息
1298      */
1299     private void addStatisticsData(Integer index, String text, Excel entity)
1300     {
1301         if (entity != null && entity.isStatistics())
1302         {
1303             Double temp = 0D;
1304             if (!statistics.containsKey(index))
1305             {
1306                 statistics.put(index, temp);
1307             }
1308             try
1309             {
1310                 temp = Double.valueOf(text);
1311             }
1312             catch (NumberFormatException e)
1313             {
1314             }
1315             statistics.put(index, statistics.get(index) + temp);
1316         }
1317     }
1318
1319     /**
1320      * 创建统计行
1321      */
1322     public void addStatisticsRow()
1323     {
1324         if (statistics.size() > 0)
1325         {
1326             Row row = sheet.createRow(sheet.getLastRowNum() + 1);
1327             Set<Integer> keys = statistics.keySet();
1328             Cell cell = row.createCell(0);
1329             cell.setCellStyle(styles.get("total"));
1330             cell.setCellValue("合计");
1331
1332             for (Integer key : keys)
1333             {
1334                 cell = row.createCell(key);
1335                 cell.setCellStyle(styles.get("total"));
1336                 cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
1337             }
1338             statistics.clear();
1339         }
1340     }
1341
1342     /**
1343      * 编码文件名
1344      */
1345     public String encodingFilename(String filename)
1346     {
1347         filename = UUID.randomUUID() + "_" + filename + ".xlsx";
1348         return filename;
1349     }
1350
1351     /**
1352      * 获取下载路径
1353      * 
1354      * @param filename 文件名称
1355      */
1356     public String getAbsoluteFile(String filename)
1357     {
1358         String downloadPath = MesConfig.getDownloadPath() + filename;
1359         File desc = new File(downloadPath);
1360         if (!desc.getParentFile().exists())
1361         {
1362             desc.getParentFile().mkdirs();
1363         }
1364         return downloadPath;
1365     }
1366
1367     /**
1368      * 获取bean中的属性值
1369      * 
1370      * @param vo 实体对象
1371      * @param field 字段
1372      * @param excel 注解
1373      * @return 最终的属性值
1374      * @throws Exception
1375      */
1376     private Object getTargetValue(T vo, Field field, Excel excel) throws Exception
1377     {
1378         Object o = field.get(vo);
1379         if (StringUtils.isNotEmpty(excel.targetAttr()))
1380         {
1381             String target = excel.targetAttr();
1382             if (target.contains("."))
1383             {
1384                 String[] targets = target.split("[.]");
1385                 for (String name : targets)
1386                 {
1387                     o = getValue(o, name);
1388                 }
1389             }
1390             else
1391             {
1392                 o = getValue(o, target);
1393             }
1394         }
1395         return o;
1396     }
1397
1398     /**
1399      * 以类的属性的get方法方法形式获取值
1400      * 
1401      * @param o
1402      * @param name
1403      * @return value
1404      * @throws Exception
1405      */
1406     private Object getValue(Object o, String name) throws Exception
1407     {
1408         if (StringUtils.isNotNull(o) && StringUtils.isNotEmpty(name))
1409         {
1410             Class<?> clazz = o.getClass();
1411             Field field = clazz.getDeclaredField(name);
1412             field.setAccessible(true);
1413             o = field.get(o);
1414         }
1415         return o;
1416     }
1417
1418     /**
1419      * 得到所有定义字段
1420      */
1421     private void createExcelField()
1422     {
1423         this.fields = getFields();
1424         this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
1425         this.maxHeight = getRowHeight();
1426     }
1427
1428     /**
1429      * 获取字段注解信息
1430      */
1431     public List<Object[]> getFields()
1432     {
1433         List<Object[]> fields = new ArrayList<Object[]>();
1434         List<Field> tempFields = new ArrayList<>();
1435         tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
1436         tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
1437         for (Field field : tempFields)
1438         {
1439             if (!ArrayUtils.contains(this.excludeFields, field.getName()))
1440             {
1441                 // 单注解
1442                 if (field.isAnnotationPresent(Excel.class))
1443                 {
1444                     Excel attr = field.getAnnotation(Excel.class);
1445                     if (attr != null && (attr.type() == Type.ALL || attr.type() == type))
1446                     {
1447                         field.setAccessible(true);
1448                         fields.add(new Object[] { field, attr });
1449                     }
1450                     if (Collection.class.isAssignableFrom(field.getType()))
1451                     {
1452                         subMethod = getSubMethod(field.getName(), clazz);
1453                         ParameterizedType pt = (ParameterizedType) field.getGenericType();
1454                         Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
1455                         this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class);
1456                     }
1457                 }
1458
1459                 // 多注解
1460                 if (field.isAnnotationPresent(Excels.class))
1461                 {
1462                     Excels attrs = field.getAnnotation(Excels.class);
1463                     Excel[] excels = attrs.value();
1464                     for (Excel attr : excels)
1465                     {
1466                         if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr())
1467                                 && (attr != null && (attr.type() == Type.ALL || attr.type() == type)))
1468                         {
1469                             field.setAccessible(true);
1470                             fields.add(new Object[] { field, attr });
1471                         }
1472                     }
1473                 }
1474             }
1475         }
1476         return fields;
1477     }
1478
1479     /**
1480      * 根据注解获取最大行高
1481      */
1482     public short getRowHeight()
1483     {
1484         double maxHeight = 0;
1485         for (Object[] os : this.fields)
1486         {
1487             Excel excel = (Excel) os[1];
1488             maxHeight = Math.max(maxHeight, excel.height());
1489         }
1490         return (short) (maxHeight * 20);
1491     }
1492
1493     /**
1494      * 创建一个工作簿
1495      */
1496     public void createWorkbook()
1497     {
1498         this.wb = new SXSSFWorkbook(500);
1499         this.sheet = wb.createSheet();
1500         wb.setSheetName(0, sheetName);
1501         this.styles = createStyles(wb);
1502     }
1503
1504     /**
1505      * 创建工作表
1506      * 
1507      * @param sheetNo sheet数量
1508      * @param index 序号
1509      */
1510     public void createSheet(int sheetNo, int index)
1511     {
1512         // 设置工作表的名称.
1513         if (sheetNo > 1 && index > 0)
1514         {
1515             this.sheet = wb.createSheet();
1516             this.createTitle();
1517             wb.setSheetName(index, sheetName + index);
1518         }
1519     }
1520
1521     /**
1522      * 获取单元格值
1523      * 
1524      * @param row 获取的行
1525      * @param column 获取单元格列号
1526      * @return 单元格值
1527      */
1528     public Object getCellValue(Row row, int column)
1529     {
1530         if (row == null)
1531         {
1532             return row;
1533         }
1534         Object val = "";
1535         try
1536         {
1537             Cell cell = row.getCell(column);
1538             if (StringUtils.isNotNull(cell))
1539             {
1540                 if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
1541                 {
1542                     val = cell.getNumericCellValue();
1543                     if (DateUtil.isCellDateFormatted(cell))
1544                     {
1545                         val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
1546                     }
1547                     else
1548                     {
1549                         if ((Double) val % 1 != 0)
1550                         {
1551                             val = new BigDecimal(val.toString());
1552                         }
1553                         else
1554                         {
1555                             val = new DecimalFormat("0").format(val);
1556                         }
1557                     }
1558                 }
1559                 else if (cell.getCellType() == CellType.STRING)
1560                 {
1561                     val = cell.getStringCellValue();
1562                 }
1563                 else if (cell.getCellType() == CellType.BOOLEAN)
1564                 {
1565                     val = cell.getBooleanCellValue();
1566                 }
1567                 else if (cell.getCellType() == CellType.ERROR)
1568                 {
1569                     val = cell.getErrorCellValue();
1570                 }
1571
1572             }
1573         }
1574         catch (Exception e)
1575         {
1576             return val;
1577         }
1578         return val;
1579     }
1580
1581     /**
1582      * 判断是否是空行
1583      * 
1584      * @param row 判断的行
1585      * @return
1586      */
1587     private boolean isRowEmpty(Row row)
1588     {
1589         if (row == null)
1590         {
1591             return true;
1592         }
1593         for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++)
1594         {
1595             Cell cell = row.getCell(i);
1596             if (cell != null && cell.getCellType() != CellType.BLANK)
1597             {
1598                 return false;
1599             }
1600         }
1601         return true;
1602     }
1603
1604     /**
1605      * 获取Excel2003图片
1606      *
1607      * @param sheet 当前sheet对象
1608      * @param workbook 工作簿对象
1609      * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
1610      */
1611     public static Map<String, PictureData> getSheetPictures03(HSSFSheet sheet, HSSFWorkbook workbook)
1612     {
1613         Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
1614         List<HSSFPictureData> pictures = workbook.getAllPictures();
1615         if (!pictures.isEmpty())
1616         {
1617             for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren())
1618             {
1619                 HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
1620                 if (shape instanceof HSSFPicture)
1621                 {
1622                     HSSFPicture pic = (HSSFPicture) shape;
1623                     int pictureIndex = pic.getPictureIndex() - 1;
1624                     HSSFPictureData picData = pictures.get(pictureIndex);
1625                     String picIndex = anchor.getRow1() + "_" + anchor.getCol1();
1626                     sheetIndexPicMap.put(picIndex, picData);
1627                 }
1628             }
1629             return sheetIndexPicMap;
1630         }
1631         else
1632         {
1633             return sheetIndexPicMap;
1634         }
1635     }
1636
1637     /**
1638      * 获取Excel2007图片
1639      *
1640      * @param sheet 当前sheet对象
1641      * @param workbook 工作簿对象
1642      * @return Map key:图片单元格索引(1_1)String,value:图片流PictureData
1643      */
1644     public static Map<String, PictureData> getSheetPictures07(XSSFSheet sheet, XSSFWorkbook workbook)
1645     {
1646         Map<String, PictureData> sheetIndexPicMap = new HashMap<String, PictureData>();
1647         for (POIXMLDocumentPart dr : sheet.getRelations())
1648         {
1649             if (dr instanceof XSSFDrawing)
1650             {
1651                 XSSFDrawing drawing = (XSSFDrawing) dr;
1652                 List<XSSFShape> shapes = drawing.getShapes();
1653                 for (XSSFShape shape : shapes)
1654                 {
1655                     if (shape instanceof XSSFPicture)
1656                     {
1657                         XSSFPicture pic = (XSSFPicture) shape;
1658                         XSSFClientAnchor anchor = pic.getPreferredSize();
1659                         CTMarker ctMarker = anchor.getFrom();
1660                         String picIndex = ctMarker.getRow() + "_" + ctMarker.getCol();
1661                         sheetIndexPicMap.put(picIndex, pic.getPictureData());
1662                     }
1663                 }
1664             }
1665         }
1666         return sheetIndexPicMap;
1667     }
1668
1669     /**
1670      * 格式化不同类型的日期对象
1671      * 
1672      * @param dateFormat 日期格式
1673      * @param val 被格式化的日期对象
1674      * @return 格式化后的日期字符
1675      */
1676     public String parseDateToStr(String dateFormat, Object val)
1677     {
1678         if (val == null)
1679         {
1680             return "";
1681         }
1682         String str;
1683         if (val instanceof Date)
1684         {
1685             str = DateUtils.parseDateToStr(dateFormat, (Date) val);
1686         }
1687         else if (val instanceof LocalDateTime)
1688         {
1689             str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDateTime) val));
1690         }
1691         else if (val instanceof LocalDate)
1692         {
1693             str = DateUtils.parseDateToStr(dateFormat, DateUtils.toDate((LocalDate) val));
1694         }
1695         else
1696         {
1697             str = val.toString();
1698         }
1699         return str;
1700     }
1701
1702     /**
1703      * 是否有对象的子列表
1704      */
1705     public boolean isSubList()
1706     {
1707         return StringUtils.isNotNull(subFields) && subFields.size() > 0;
1708     }
1709
1710     /**
1711      * 是否有对象的子列表,集合不为空
1712      */
1713     public boolean isSubListValue(T vo)
1714     {
1715         return StringUtils.isNotNull(subFields) && subFields.size() > 0 && StringUtils.isNotNull(getListCellValue(vo)) && getListCellValue(vo).size() > 0;
1716     }
1717
1718     /**
1719      * 获取集合的值
1720      */
1721     public Collection<?> getListCellValue(Object obj)
1722     {
1723         Object value;
1724         try
1725         {
1726             value = subMethod.invoke(obj, new Object[] {});
1727         }
1728         catch (Exception e)
1729         {
1730             return new ArrayList<Object>();
1731         }
1732         return (Collection<?>) value;
1733     }
1734
1735     /**
1736      * 获取对象的子列表方法
1737      * 
1738      * @param name 名称
1739      * @param pojoClass 类对象
1740      * @return 子列表方法
1741      */
1742     public Method getSubMethod(String name, Class<?> pojoClass)
1743     {
1744         StringBuffer getMethodName = new StringBuffer("get");
1745         getMethodName.append(name.substring(0, 1).toUpperCase());
1746         getMethodName.append(name.substring(1));
1747         Method method = null;
1748         try
1749         {
1750             method = pojoClass.getMethod(getMethodName.toString(), new Class[] {});
1751         }
1752         catch (Exception e)
1753         {
1754             log.error("获取对象异常{}", e.getMessage());
1755         }
1756         return method;
1757     }
1758 }