1. package com.ai.hdl.market.infrastructure.utils.easyexcel;
    2. import com.ai.hdl.market.infrastructure.utils.AppContextUtil;
    3. import com.alibaba.excel.annotation.ExcelProperty;
    4. import com.alibaba.excel.write.handler.SheetWriteHandler;
    5. import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
    6. import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
    7. import org.apache.commons.lang.StringUtils;
    8. import org.apache.poi.ss.usermodel.*;
    9. import org.apache.poi.ss.util.CellRangeAddressList;
    10. import org.apache.poi.xssf.usermodel.XSSFDataValidation;
    11. import org.hibernate.validator.constraints.Length;
    12. import javax.validation.constraints.Max;
    13. import javax.validation.constraints.Min;
    14. import java.lang.reflect.Field;
    15. import java.math.BigDecimal;
    16. import java.util.Arrays;
    17. import java.util.List;
    18. public class ExplicitWriteHandler implements SheetWriteHandler {
    19. private static Class<?> clazz;
    20. private int lineNum;
    21. private final List<Class<?>> numClassList = Arrays.asList(Float.class, Double.class, BigDecimal.class, Integer.class,
    22. Short.class, Byte.class);
    23. public ExplicitWriteHandler(Class<?> clazz) {
    24. ExplicitWriteHandler.clazz = clazz;
    25. this.lineNum = 1000;
    26. }
    27. public void lineNum(int num) {
    28. this.lineNum = num;
    29. }
    30. @Override
    31. public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    32. }
    33. @Override
    34. public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
    35. Sheet sheet = writeSheetHolder.getSheet();
    36. sheet.createFreezePane(0, 1, 0, 1);
    37. DataValidationHelper helper = sheet.getDataValidationHelper();
    38. Field[] declaredFields = clazz.getDeclaredFields();
    39. for (int i = 0; i < declaredFields.length; i++) {
    40. Field field = declaredFields[i];
    41. int columnIndex = i;
    42. //解析注解信息
    43. ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
    44. if (excelProperty != null) {
    45. columnIndex = excelProperty.index();
    46. }
    47. ExplicitConstraint explicitConstraint = field.getAnnotation(ExplicitConstraint.class);
    48. String[] explicitArray = resolveExplicitConstraint(explicitConstraint);
    49. if (explicitArray != null && explicitArray.length > 0) {
    50. explicitFormat(columnIndex, explicitArray, sheet, helper);
    51. }
    52. ExcelDateFormat format = field.getAnnotation(ExcelDateFormat.class);
    53. if (format != null) {
    54. dateCellFormat(columnIndex, format.format(), sheet, helper);
    55. }
    56. Class<?> fieldType = field.getType();
    57. if (numClassList.contains(fieldType)) {
    58. numberCellValid(columnIndex, field, fieldType, sheet, helper);
    59. }
    60. if (fieldType.equals(String.class)) {
    61. textCellStyle(columnIndex, sheet);
    62. }
    63. Length length = field.getAnnotation(Length.class);
    64. if (length != null) {
    65. textLengthValid(columnIndex, length.min(), length.max(), sheet, helper);
    66. }
    67. }
    68. }
    69. private void textCellStyle(Integer columnIndex, Sheet sheet) {
    70. Workbook book = sheet.getWorkbook();
    71. CellStyle cellStyle = book.createCellStyle();
    72. DataFormat dataFormat = book.createDataFormat();
    73. cellStyle.setDataFormat(dataFormat.getFormat("@"));
    74. cellStyle.setWrapText(false);
    75. sheet.setDefaultColumnStyle(columnIndex, cellStyle);
    76. }
    77. private void textLengthValid(Integer columnIndex, Integer min, Integer max, Sheet sheet, DataValidationHelper helper) {
    78. CellRangeAddressList addressList = new CellRangeAddressList(1, lineNum, columnIndex, columnIndex);
    79. int opType = DataValidationConstraint.OperatorType.BETWEEN;
    80. DataValidationConstraint constraint = helper.createTextLengthConstraint(opType, Integer.toString(min), Integer.toString(max));
    81. DataValidation dataValidation = helper.createValidation(constraint, addressList);
    82. //处理Excel兼容性问题
    83. setDataValidation(dataValidation, "数据长度超出限制[" + min + "~" + max + "]");
    84. sheet.addValidationData(dataValidation);
    85. }
    86. private void explicitFormat(Integer columnIndex, String[] sources, Sheet sheet, DataValidationHelper helper) {
    87. // 起始行、终止行、起始列、终止列
    88. CellRangeAddressList addressList = new CellRangeAddressList(1, lineNum, columnIndex, columnIndex);
    89. //设置下拉框数据
    90. DataValidationConstraint constraint = helper.createExplicitListConstraint(sources);
    91. DataValidation dataValidation = helper.createValidation(constraint, addressList);
    92. //处理Excel兼容性问题
    93. setDataValidation(dataValidation, null);
    94. sheet.addValidationData(dataValidation);
    95. }
    96. private void numberCellValid(Integer columnIndex, Field field, Class<?> clazz, Sheet sheet, DataValidationHelper helper) {
    97. int opType = DataValidationConstraint.OperatorType.BETWEEN;
    98. int vType = DataValidationConstraint.ValidationType.INTEGER;
    99. if (clazz.equals(Float.class) || clazz.equals(Double.class) || clazz.equals(BigDecimal.class)) {
    100. vType = DataValidationConstraint.ValidationType.DECIMAL;
    101. }
    102. Min minAnnotation = field.getAnnotation(Min.class);
    103. Max maxAnnotation = field.getAnnotation(Max.class);
    104. String min = minAnnotation == null ? "0" : Long.toString(minAnnotation.value());
    105. String max = maxAnnotation == null ? "99999999" : Long.toString(maxAnnotation.value());
    106. CellRangeAddressList addressList = new CellRangeAddressList(1, lineNum, columnIndex, columnIndex);
    107. DataValidationConstraint constraint = helper.createNumericConstraint(vType, opType, min, max);
    108. DataValidation dataValidation = helper.createValidation(constraint, addressList);
    109. setDataValidation(dataValidation, "请输入正确的数值");
    110. sheet.addValidationData(dataValidation);
    111. }
    112. private void dateCellFormat(Integer columnIndex, String format, Sheet sheet, DataValidationHelper helper) {
    113. Workbook book = sheet.getWorkbook();
    114. CellStyle cellStyle = book.createCellStyle();
    115. short dateFmt = book.createDataFormat().getFormat(format);
    116. cellStyle.setDataFormat(dateFmt);
    117. sheet.setDefaultColumnStyle(columnIndex, cellStyle);
    118. int opType = DataValidationConstraint.OperatorType.BETWEEN;
    119. String minDate = "Date(1900, 1, 1)";
    120. String maxDate = "Date(3000, 1, 1)";
    121. CellRangeAddressList addressList = new CellRangeAddressList(1, lineNum, columnIndex, columnIndex);
    122. DataValidationConstraint constraint = helper.createDateConstraint(opType, minDate, maxDate, format);
    123. DataValidation dataValidation = helper.createValidation(constraint, addressList);
    124. setDataValidation(dataValidation, "请输入[" + format + "]格式日期");
    125. sheet.addValidationData(dataValidation);
    126. }
    127. private void setDataValidation(DataValidation dataValidation, String errorMsg) {
    128. if (dataValidation instanceof XSSFDataValidation) {
    129. dataValidation.setSuppressDropDownArrow(true);
    130. dataValidation.setShowErrorBox(true);
    131. if (StringUtils.isNotBlank(errorMsg)) {
    132. dataValidation.createErrorBox("温馨提示", errorMsg);
    133. }
    134. } else {
    135. dataValidation.setSuppressDropDownArrow(false);
    136. if (StringUtils.isNotBlank(errorMsg)) {
    137. dataValidation.createPromptBox("温馨提示", errorMsg);
    138. }
    139. }
    140. }
    141. private String[] resolveExplicitConstraint(ExplicitConstraint explicitConstraint) {
    142. if (explicitConstraint == null) {
    143. return null;
    144. }
    145. //固定下拉信息
    146. String[] source = explicitConstraint.source();
    147. if (source.length <= 0) {
    148. //动态下拉信息
    149. @SuppressWarnings("unchecked")
    150. Class<? extends ExplicitConstraint.IExplicitInterface>[] classes = explicitConstraint.sourceClass();
    151. if (classes.length > 0) {
    152. ExplicitConstraint.IExplicitInterface explicitInterface = AppContextUtil.getBean(classes[0]);
    153. source = explicitInterface.source();
    154. }
    155. }
    156. if (source == null || source.length <= 0) {
    157. source = null;
    158. }
    159. return source;
    160. }
    161. }