DropDownOptions.java 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package com.ruoyi.common.excel;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.ruoyi.common.exception.ServiceException;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import lombok.NoArgsConstructor;
  7. import java.util.ArrayList;
  8. import java.util.HashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11. /**
  12. * <h1>Excel下拉可选项</h1>
  13. * 注意:为确保下拉框解析正确,传值务必使用createOptionValue()做为值的拼接
  14. *
  15. * @author Emil.Zhang
  16. */
  17. @Data
  18. @AllArgsConstructor
  19. @NoArgsConstructor
  20. @SuppressWarnings("unused")
  21. public class DropDownOptions {
  22. /**
  23. * 一级下拉所在列index,从0开始算
  24. */
  25. private int index = 0;
  26. /**
  27. * 二级下拉所在的index,从0开始算,不能与一级相同
  28. */
  29. private int nextIndex = 0;
  30. /**
  31. * 一级下拉所包含的数据
  32. */
  33. private List<String> options = new ArrayList<>();
  34. /**
  35. * 二级下拉所包含的数据Map
  36. * <p>以每一个一级选项值为Key,每个一级选项对应的二级数据为Value</p>
  37. */
  38. private Map<String, List<String>> nextOptions = new HashMap<>();
  39. /**
  40. * 分隔符
  41. */
  42. private static final String DELIMITER = "_";
  43. /**
  44. * 创建只有一级的下拉选
  45. */
  46. public DropDownOptions(int index, List<String> options) {
  47. this.index = index;
  48. this.options = options;
  49. }
  50. /**
  51. * <h2>创建每个选项可选值</h2>
  52. * <p>注意:不能以数字,特殊符号开头,选项中不可以包含任何运算符号</p>
  53. *
  54. * @param vars 可选值内包含的参数
  55. * @return 合规的可选值
  56. */
  57. public static String createOptionValue(Object... vars) {
  58. StringBuilder stringBuffer = new StringBuilder();
  59. String regex = "^[\\S\\d\\u4e00-\\u9fa5]+$";
  60. for (int i = 0; i < vars.length; i++) {
  61. String var = StrUtil.trimToEmpty(String.valueOf(vars[i]));
  62. if (!var.matches(regex)) {
  63. throw new ServiceException("选项数据不符合规则,仅允许使用中英文字符以及数字");
  64. }
  65. stringBuffer.append(var);
  66. if (i < vars.length - 1) {
  67. // 直至最后一个前,都以_作为切割线
  68. stringBuffer.append(DELIMITER);
  69. }
  70. }
  71. if (stringBuffer.toString().matches("^\\d_*$")) {
  72. throw new ServiceException("禁止以数字开头");
  73. }
  74. return stringBuffer.toString();
  75. }
  76. /**
  77. * 将处理后合理的可选值解析为原始的参数
  78. *
  79. * @param option 经过处理后的合理的可选项
  80. * @return 原始的参数
  81. */
  82. public static List<String> analyzeOptionValue(String option) {
  83. return StrUtil.split(option, DELIMITER, true, true);
  84. }
  85. }